Skip to the page

Core data model · core

Default arguments, copies and changing a list while looping

Default values are built once, when def runs, so a mutable default is shared by every call. A plain assignment copies nothing, a shallow copy shares the inner objects, and a deep copy duplicates everything.

The notes

What you must know

  • Defaults are evaluated once when def runs and stored on the function (add_tag.defaults). A call without the argument gets the same list every time.
  • Fix: tags=None, then if tags is None: tags = [] inside. The same goes for dict and set defaults. tags=list() is still evaluated once.
  • A dataclass refuses a mutable default (ValueError) and wants field(default_factory=list). Ruff and flake8-bugbear flag it as rule B006.
  • b = a copies nothing. A shallow copy (a[:], list(a), a.copy(), copy.copy) makes a new outer container with the same inner objects. copy.deepcopy copies recursively.
  • [[0] * 3] * 3 makes three references to one row. Use [[0] * 3 for _ in range(3)].
  • deepcopy is slow on big structures because it walks every object in Python, and it can fail on locks and sockets. Immutable data needs no copy.
  • Removing items from a list while looping over it skips the item after each removed one, because the later items shift left. Build a new list, use nums[:] = [...], or loop over a copy.
  • Changing the size of a dict or set while iterating raises RuntimeError.

The red pen

Common traps: mistake → fix

  • Mistake: tags=list() fixes the shared default

    Fix: it is still evaluated once at def time; use None.

  • Mistake: a[:] is a deep copy

    Fix: it is shallow; the inner objects are shared.

  • Mistake: Use deepcopy everywhere to be safe

    Fix: it costs time and hides code that changes shared data by mistake.

  • Mistake: Python handles removing items inside a for loop

    Fix: it silently skips items.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does add_tag("urgent") then add_tag("billing") return when tags=[] is the default?
  2. What is the difference between b = a, copy.copy(a) and copy.deepcopy(a) for a list of dicts?
  3. Why does [[0] * 3] * 3 behave strangely?
  4. What does nums = [2, 4, 5, 6, 8, 9] print after a loop that removes evens with nums.remove(n)?
  5. When is deepcopy a bad choice in a hot code path?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview