Problem No 16
Write a function that avoids mutable default args
Medium≈ 13 minute session
Lesson guide
What this Python exercise practices
Write a function that avoids mutable default args is a intermediate practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 13 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 13 minutes
Practice path
Summary
Learn how to write functions that use immutable defaults to avoid shared mutable state between calls.
Problem statement
In Python, using a mutable object (like a list) as a default argument is a common pitfall because the same object is reused across calls. Your task is to implement append_to(element, lst=None) that appends element to lst and returns the list. If lst is not provided (None), create and use a new list for that call so calls don't share state.
Task
Implement a function that safely appends an element to a list without using a mutable default argument.
Examples
Basic usage
Input
append_to(1)
Output
[1]
Explanation
When called without a list, append_to should create a new list and return [1].
Input format
A function call append_to(element, lst=None). element may be any value; lst is optional.
Output format
Return the list after appending the element. The returned value will be shown as a Python list string representation.
Constraints
Do not use a mutable object as a default value. If lst is None, create a new list inside the function.
Samples
Sample input 0
append_to('a', ['b'])
Sample output 0
['b', 'a']
Explanation 0
When a list is provided, append the element to it and return the same list.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.