PythiloEasy · 10 min · Task 6 of 20 · progress kept in this browser

The shared default

An interviewer shows you this and asks why it misbehaves:

def add_tag(tag, tags=[]):
    tags.append(tag)
    return tags

print(add_tag("a"))  # ['a']
print(add_tag("b"))  # ['a', 'b']

Default values are created once, when def runs, and stored on the function. You can see the stored list in add_tag.__defaults__. Every call that omits tags gets that same list, so changes accumulate.

Numbers and strings do not show the problem, because they cannot be changed in place. Lists, dicts and sets do.

The standard fix uses None as a marker and creates the object inside the function:

def f(items=None):
    if items is None:
        items = []

Test with is None and not if not items, so an empty list passed by the caller is still the caller's list.

Your task

Fix add_tag(tag, tags=None) so each call without tags starts from a new list. A list passed in must be appended to and returned, even if it is empty.