Skip to content

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:

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 1A default value is evaluated once, when def runs, and that same list object is reused by every call.
Hint 2Use None as the default and create the list inside the function.
Hint 3list(tags) + [tag] builds a new list without touching the caller's.

Learn the concepts

More Python problems

All Python problems