Skip to content
Bronze 4 min read · Idioms 2 practice problems ↓

Mutability, copies and default arguments

Some of the hardest Python bugs come from data changing when you did not touch it: a list edited through another name, a default argument that remembers last time. They all come from one idea, that a name points at an object and does not hold a copy. This lesson makes that idea visible.

Foundations · Python for data engineers · Bronze · Everyday idioms, lesson 2 of 3

Read first: Lists, dicts and sets: what each operation costs (skip if you know it)

In plain words first

Two friends share one shopping list on the fridge. If one of them crosses off milk, the other sees it crossed off too: there is only one list, with two people pointing at it. To keep your own version, you have to make a photocopy.

Python variables work like the friends: b = a does not photocopy the list, it adds a second name pointing at the same one. Numbers and strings cannot be crossed out, so this only matters for things that can change: lists, dicts, sets and your own objects.

Names point at objects

Assignment never copies. route = stops makes route another name for the same list, so changing the object through one name is visible through the other. Strings, numbers and tuplestuple: An ordered, immutable sequence like ("Pune", 2026). Because it cannot change, it can be a dict key; use it for small fixed records. Learn more → cannot change (they are immutable), so this only bites with lists, dicts, sets and your own objects.

Python · two names, one list
stops = ["kitchen", "gate"]
route = stops
route.append("door")
print("stops:", stops)
print("same list?", route is stops)

Output from a real run

stops: ['kitchen', 'gate', 'door']
same list? True

Shallow and deep copies

list(x), x.copy(), x[:] and {**d} make a shallow copy: a new outer container holding the same inner objects. copy.deepcopy copies every level. With nested data (configs, JSON), a shallow copy still shares the inner dicts and lists.

Python · a shallow copy shares the nested dict
import copy

settings = {"city": "Pune", "fees": {"base": 20}}
shallow = settings.copy()
deep = copy.deepcopy(settings)

shallow["fees"]["base"] = 35
print("original:", settings["fees"])  # changed through the shallow copy
print("deep copy:", deep["fees"])  # still its own dict

Output from a real run

original: {'base': 35}
deep copy: {'base': 20}

The mutable default argument

Default values are evaluated once, when def runs, and stored on the function. A [] or {} default is therefore one object shared by every call that uses the default.

Python · the bug and the fix
def add_item_bad(item, basket=[]):
    basket.append(item)
    return basket


def add_item(item, basket=None):
    basket = [] if basket is None else list(basket)
    basket.append(item)
    return basket


add_item_bad("chai")
print("bad, second call:", add_item_bad("vada"))  # chai is still there
add_item("chai")
print("fixed, second call:", add_item("vada"))

Output from a real run

bad, second call: ['chai', 'vada']
fixed, second call: ['vada']

The fix uses None as a sentinel and creates the list inside the body. Copying with list(basket) also leaves a caller's list untouched.

Do not change what you were given

Functions in a pipeline should return new data instead of mutating their arguments: the caller may still use the input, and a retry that runs the function twice must see the original. Copy at the boundary (deep copy for nested data), then change the copy.

Immutable values are safe to share: Tuples, strings and frozensets can be shared freely. A tuple that contains a list is still mutable inside, though: immutability is only as deep as its contents.

Common mistakes

  • def f(x, acc=[]) — The list is shared across calls. Default to None and create it inside.
  • Copying nested data with .copy() — Inner dicts and lists stay shared. Use copy.deepcopy.
  • Modifying an argument in place — Surprises the caller and breaks retries. Return a new object.

Key takeaways

  • Assignment binds a name; it never copies.
  • Shallow copies share inner objects; deepcopy copies every level.
  • Mutable defaults are created once and shared; use None.
  • Return new data instead of mutating inputs.

Interview prep

THE QUESTION

"Why does def add(x, items=[]) keep values between calls?"

Default arguments are evaluated once, when the def statement runs, and stored on the function object (in __defaults__). Every call that relies on the default gets that same list, so appends accumulate. The idiom is a None default and creating the list in the body: items = [] if items is None else items. The same applies to dicts, sets and any mutable object.

Avoid: "b = a.copy() means changing b never affects a". Only the top level is copied; nested objects are shared.

Follow-ups · answer out loud, then open

Follow-up"Is Python pass-by-value or pass-by-reference?"
Neither, exactly: arguments are passed by object reference (call by sharing). The function gets a new name for the same object, so mutating it is visible to the caller, but rebinding the parameter name is not.
Scenario"A config dict is shared by several pipeline steps, and one step's override leaked into the others. How do you prevent it?"
Each step works on copy.deepcopy(config) and returns a new config instead of mutating the shared one, or the base config is frozen (MappingProxyType, frozen dataclasses). Overrides then stay local to the step that made them.
Trap"A tuple is immutable, so its contents can never change."
The tuple cannot be rebound to other objects, but a list inside it can still be mutated: t = ([],); t[0].append(1) works. Such a tuple is also unhashable.

Check yourself

3 questions

a = [1]; b = a; b.append(2). What is a?

Show the answer

[1, 2]. a and b are the same list.

Which copies nested dicts too?

Show the answer

copy.deepcopy(d). The others are shallow.

When is a default argument value created?

Show the answer

When def runs. Once, when the function is defined.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Everyday idioms · lesson 3 of 3 · 8 min read
Functions, *args, **kwargs and closures
Every kind of parameter, closures that remember state, nonlocal and late binding.

Related lessons

Previous: Sorting with key functions

Primary sources: copy: shallow and deep copy · Default argument values