Why Does My Python Function Keep Tags From an Earlier Call?

Asked 18 hours ago 20 views

0

I wrote a small helper that adds a tag to a list. If no list is supplied, I expected it to start with an empty one each time.

def add_tag(tag, tags=[]):
    # Add the new tag to the supplied list.
    tags.append(tag)
    return tags


# These calls are intended to create independent lists.
print(add_tag("python"))
print(add_tag("seo"))

The output is:

  • First call: ['python']
  • Second call: ['python', 'seo']

Why is the second call using the earlier list? Is this specific to mutable default arguments, or can it happen with defaults such as strings and numbers too?

What is the usual way to give each omitted argument a fresh list while still allowing callers to pass an existing list that the function deliberately modifies?

0 Answers


Write Your Answer