Why is a mutable default argument dangerous?

Python control flow and functions · Freshers and experienced

Model answer

Default values are created once when the function is defined. def add(item, items=[]) reuses the same list across calls, so items accumulate. Use None and create a new list inside: if items is None: items = [].

Learn this topic

Functions in Python: def, Arguments and return in the course Python for Beginners: Learn to Code with Real Projects.

Sign in to add your own answer.

More questions