12. Fix the Mutable Default Argument
Difficulty: Medium · Topic: Core Python & data structures
This function is meant to return a list of tags with one more tag added:
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
But add_tag('a') followed by add_tag('b') returns ['a', 'b'], and the lists people pass in get changed. Fix it:
- Called without
tags(or withtags=None), it returns a new list holding justtag. - Called with a list, it returns a new list: the given tags, then
tag. The caller's list is not modified.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
add_tag('a')
add_tag('b')Expected: ['b']
Hints
Hint 1
A default value is evaluated once, whendef runs, and that same list object is reused by every call.Hint 2
UseNone as the default and create the list inside the function.Hint 3
list(tags) + [tag] builds a new list without touching the caller's.Learn the concepts
- Mutability, copies and default arguments · 4 min read. What assignment really does, shallow versus deep copies, and the mutable default trap.
More Python problems
- Flatten a Nested List · Easy
- Squares of the Even Numbers · Easy
- Top K Frequent Words · Easy
- Invert a Dictionary · Easy
- Merge Dicts and Sum Shared Keys · Easy
- Group Records by Key · Easy
- Count Words in Reviews · Easy
- Zip Columns into Records · Easy
- Find the Missing IDs · Easy
- Safe Min and Max · Easy
- Sort by Several Keys · Medium
- Override a Config Without Changing It · Medium
- Keep the Last N Events · Medium