MediumConcept

Why should you not use a mutable default argument in Python?

Technology:
Python
Experience:
Junior,
Mid-level

Quick answer

Default argument values are evaluated once when the function is defined, so a default list or dictionary is shared between every call that does not pass its own, causing data to leak between calls.

Detailed explanation

This is one of the most common Python gotchas. The fix is to use None as the default and create a new object inside the function.

Example

python
def add_item(item, items=[]):        # bug: one shared list
    items.append(item)
    return items

add_item("a")   # ['a']
add_item("b")   # ['a', 'b']  <- surprise

def add_item(item, items=None):      # correct
    if items is None:
        items = []
    items.append(item)
    return items
  • PythonEasy

    What are *args and **kwargs in Python?

    *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary, which lets a function accept a variable number of arguments.

    Junior 路 Mid-level 路 Functions & Scope
  • PythonMedium

    What are decorators in Python and how do they work?

    A decorator is a function that takes another function and returns a modified version of it, letting you add behaviour such as logging, caching or access control without changing the original code.

    Mid-level 路 Senior 路 Functions & Scope
  • PythonMedium

    What are generators and the yield keyword in Python?

    A generator is a function that uses yield to produce values one at a time and remembers its state between calls, so it can process large or infinite sequences without holding everything in memory.

    Mid-level 路 Senior 路 Functions & Scope
  • PythonEasy

    What is the difference between a list and a tuple in Python?

    A list is mutable and can be changed after creation, while a tuple is immutable; tuples are slightly faster, use less memory and can be used as dictionary keys when their items are hashable.

    Intern 路 Junior 路 Data Structures