easy +8 pts

Default Argument Trap

Avoid mutable default arguments and make your function safe across calls.

In Python, using a mutable default argument like `def add_item(item, bag=[])` causes the same list to be shared across all calls, leading to unexpected behavior. Your task is to implement a function `add_item(item, bag=None)` that adds an item to a shopping bag. If `bag` is not provided (i.e., `None`), the function should create a new empty list, add the item to it, and return the list. If `bag` is provided, add the item to that list and return it. The function must not modify the default argument in any way. It should work correctly when called multiple times without a `bag` argument, each time returning a new list containing only the given item. **Function signature:** `def add_item(item, bag=None):` **Behavior:** - When `bag` is `None`, a new list `[item]` is returned. - When `bag` is a list, the item is appended and the same list is returned. - The original list passed as `bag` should be modified (append) as expected. Do not use any external libraries. Your solution should be a pure Python function.

Constraints

- `item` can be any hashable or unhashable Python object (numbers, strings, tuples, lists, etc.). - `bag` is either `None` or a list. - The function should return a list. - Complexity: O(1) append.

Example

>>> add_item('apple')
['apple']
>>> add_item('banana')
['banana']
>>> my_bag = ['apple']
>>> add_item('banana', my_bag)
['apple', 'banana']
>>> my_bag
['apple', 'banana']
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Check if bag is None inside the function and create a new list then.
Remember that if bag is not None, you should append to it and return it.
Avoid using a mutable default argument like `bag=[]`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.