Fix the Mutable Default Argument Bug

Medium ⏱ 12 min 46% acceptance ★★★★★ 4.7
The function add_item(item, cart=[]) is buggy: because the default list is created once and shared across calls, items from previous calls leak into later ones. Rewrite add_item so each call with no cart argument starts from a fresh empty list, while still allowing a caller to pass in and extend their own list. Return the resulting list.

Examples

Example 1
Input
add_item("apple")
add_item("banana")
Output
['apple'], ['banana']
Explanation

Each call without a cart argument must produce an independent list, not accumulate across calls.

Example 2
Input
add_item("milk", ["bread"])
Output
['bread', 'milk']
Explanation

When a cart is supplied, the item is appended to it.

Constraints

  • Never use a mutable object (like []) directly as a default parameter value.

Topics

Functionsmutable default arguments

Companies

NetflixCisco

Hints

Hint 1

Use None as the default sentinel value, then create a new list inside the function body when cart is None.

Hint 2

Remember to append item before returning.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.