Problem No 6
Implement a function with a default argument
Easy≈ 10 minute session
Lesson guide
What this Python exercise practices
Implement a function with a default argument is a beginner practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 10 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Beginner
- Estimated time
- 10 minutes
Practice path
Summary
Practice using default arguments safely by creating a function that appends an item to a list, avoiding the common mutable-default pitfall.
Problem statement
Implement a function append_item(item, lst=None) that appends item to the list lst and returns the resulting list. If lst is omitted or None, the function should create and return a new list containing only item. Do not use a mutable object as a default argument (e.g., avoid lst=[] in the signature). The function must ensure separate calls with the default create distinct lists.
Task
Write append_item(item, lst=None) that appends item to lst. If lst is not provided, create a fresh list each call.
Examples
Default list creation
Input
append_item(1)
Output
[1]
Explanation
No list provided; a new list [1] is created and returned.
Input format
First argument: item to append. Second optional argument: list to append to (or None to use a new list).
Output format
The list after appending the item.
Constraints
Ensure that a new list is created when lst is None. Do not mutate a shared default list across calls.
Samples
Sample input 0
append_item('a', ['x'])
Sample output 0
['x', 'a']
Explanation 0
Appends 'a' to the provided list ['x'] and returns it.
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.