Skip to content

Lesson 21 of 52Objects

The Python Memory Model

See names as labels on objects, so aliasing, mutation, copying and argument passing never surprise you again.

17 min read0/5 questions

"I changed one list and another one changed too." Almost every Python developer hits this bug, and it shows up again in code review, in debugging sessions and in interviews. The cure is one mental model: names are labels attached to objects, not boxes that hold values. Once you see it, a whole family of bugs becomes obvious.

Everything is an object

In Python, every value is an object: numbers, strings, lists, functions, classes, even None. Every object has three things:

  • an identity: which object it is, which never changes (id(x) shows it as a number),
  • a type: what kind of object it is (type(x)),
  • a value: the data it holds.
Python
def greet(): return "hi" for thing in [42, "text", [1, 2], greet, None, int]: print(type(thing).__name__, isinstance(thing, object))
Output
Press Run (⌘ Enter) to see what happens.

Even functions and classes are objects. That is why you can store a function in a list or pass a class to another function.

Names point to objects

An assignment like a = [1, 2] does two things: it creates a list object, then it binds the name a to it. The name is a label. Writing b = a does not copy anything. It attaches a second label to the same object.

Two names, one list
a = [1, 2]
NamesObjects in memoryalist[1, 2]

Python builds a list object and binds the name a to it.

1/4

That last step holds the key distinction of this lesson:

  • Mutating changes the object itself (append, x[0] = ..., d["k"] = ..., .sort()). Every name pointing to it sees the change.
  • Rebinding points a name at a different object (x = ...). Other names are unaffected.
Predict the outputPython

What does this print?

a = [1, 2, 3]
b = a
b[0] = 99
b = [0]
print(a)
Need a nudge? Hints walk you through it.

Identity vs equality: is vs ==

== asks "do these have the same value?" and calls __eq__. is asks "are these the same object?" and compares identities. Two separate lists can be equal without being identical.

Python
a = [1, 2]b = [1, 2]c = aprint(a == b, a is b) # equal values, different objectsprint(a == c, a is c) # same objectprint(id(a) == id(c)) x = Noneprint(x is None) # the right way to test for None
Output
Press Run (⌘ Enter) to see what happens.

Use is only for singletons, objects of which only one exists: None, True, False. For everything else use ==.

Quick check
Which line is the idiomatic way to check that result has no value?
Need a nudge? A hint rules out a wrong answer.

Mutable and immutable types

Some types can never change after creation. They are immutable: int, float, bool, str, tuple, frozenset, bytes, None. Operations on them build new objects. Others are mutable and can change in place: list, dict, set, and most objects of your own classes.

+= on a string vs a list
s = "hi"
t = s
NamesObjects in memoryststr"hi"

Two names, one string object.

1/4
Predict the outputPython

What does this print?

a = (1, 2)
b = a
a += (3,)
x = [1, 2]
y = x
x += [3]
print(len(b), len(y))
Need a nudge? Hints walk you through it.

Passing arguments: by object reference

Is Python "pass by value" or "pass by reference"? Neither, exactly. When you call f(x), the parameter inside the function becomes another name for the same object. This is often called pass by assignment or pass by object reference: it is exactly as if the function ran param = x first.

So the same two rules apply. If the function mutates the object, the caller sees it. If the function rebinds its parameter, the caller does not.

Python
def add_item(items): items.append("new") # mutates the caller's list def replace(items): items = ["fresh"] # rebinds the local name only def bump(n): n += 1 # ints are immutable: rebinds locally shopping = ["milk"]add_item(shopping)replace(shopping)count = 5bump(count)print(shopping, count)
Output
Press Run (⌘ Enter) to see what happens.

This explains the famous mutable default argument bug. A default value is evaluated once, when def runs, and that one object is reused on every call.

Python
def add_tag(tag, tags=[]): # one list, created once tags.append(tag) return tags print(add_tag("a"))print(add_tag("b")) # surprise: ['a', 'b'] def add_tag_fixed(tag, tags=None): # the standard fix if tags is None: tags = [] tags.append(tag) return tags print(add_tag_fixed("a"), add_tag_fixed("b"))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
def clear(d): d = {} is called as clear(config). What is config afterwards?
Need a nudge? A hint rules out a wrong answer.

Shallow vs deep copy

When you do want an independent copy, you have two levels:

  • A shallow copy (list(x), x[:], x.copy(), dict(d), copy.copy(x)) creates a new outer container, but its items are the same objects as before.
  • A deep copy (copy.deepcopy(x)) recursively copies everything inside too.

For a flat list of numbers, a shallow copy is enough. For nested data (a list of lists, a dict of lists) a shallow copy still shares the inner objects.

Shallow copy of a grid
grid = [[0, 0], [0, 0]]
NamesObjects in memorygridlist[r1, r2]list[0, 0]list[0, 0]

The outer list holds references to two row lists.

1/4
Python
import copy grid = [[0, 0], [0, 0]]shallow = grid.copy()deep = copy.deepcopy(grid)shallow[0][0] = 7print(grid) # changed through the shared rowprint(deep) # independent # The classic trap: multiplying a list of listsboard = [[0] * 3] * 3board[0][0] = 1print(board) # three references to ONE rowboard = [[0] * 3 for _ in range(3)]board[0][0] = 1print(board)
Output
Press Run (⌘ Enter) to see what happens.
Put it in order3 steps

Order these from 'shares the most' to 'shares the least' with the original nested list x.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

How memory is freed

You never free memory by hand in Python. CPython, the standard interpreter, uses reference counting: every object tracks how many references point to it. When the count drops to zero (the last name is rebound or goes out of scope, or the container holding it is gone), the object is freed immediately.

Reference counting alone cannot free cycles: two objects that point to each other keep each other's count above zero. So CPython also runs a cyclic garbage collector (the gc module) every so often to find and free groups of objects that only reference each other.

Python
import sys, gc data = []print(sys.getrefcount(data)) # includes the temporary reference from the call itselfalias = dataprint(sys.getrefcount(data)) # one more name, one more reference a, b = [], []a.append(b); b.append(a) # a cycledel a, b # unreachable, but counts are not zeroprint("collected objects:", gc.collect() >= 2)
Output
Press Run (⌘ Enter) to see what happens.

del x deletes the name, not the object. The object goes away only when nothing else refers to it.

Under the hood: small int caching

CPython creates the integers from -5 to 256 once at startup and reuses them, because they are used everywhere. So a = 100; b = 100; a is b is True, while the same test with bigger numbers may be True or False depending on how the code was compiled. Short strings that look like identifiers are often reused too (interning).

a = 256
b = 256
a is b   # True in CPython, but do not rely on it

This is an implementation detail of CPython, not part of the language. Other interpreters may differ, and the exact behaviour can change between versions. The lesson: never use is to compare numbers or strings. Use ==.

ChallengeEasy

Fix the mutable default

This function has the classic mutable default argument bug: calls that do not pass tags all share one list.

add_tag("a")   # ["a"]
add_tag("b")   # should be ["b"], but the buggy version returns ["a", "b"]

Fix add_tag so that:

  • when tags is not passed, each call starts from a new empty list,
  • when the caller passes their own list, the tag is appended to that list (mutating it) and the same list is returned.
Python
def add_tag(tag: str, tags: list[str] = []) -> list[str]: # Bug: the default list is created once and shared by every call. tags.append(tag) return tags
ChallengeEasy

Clone a grid

Write clone_grid(grid) that returns a copy of a 2D list (a list of rows) that is fully independent: changing a cell in the copy must never change the original, and vice versa.

g = [[1, 2], [3, 4]]
c = clone_grid(g)
c[0][0] = 99
g        # still [[1, 2], [3, 4]]

A shallow copy like grid.copy() is not enough, because the rows would still be shared. Try it without the copy module.

Python
def clone_grid(grid: list[list[int]]) -> list[list[int]]: # Return a new outer list AND new row lists. pass
Key terms
name binding
Attaching a name to an object. b = a binds a second name to the same object; nothing is copied.
mutation vs rebinding
Mutation changes an object in place (seen by every alias). Rebinding points one name at a different object.
is vs ==
is checks identity (same object); == checks value via __eq__. Use is only for None, True, False.
pass by assignment
Function parameters are new names for the caller's objects, as if param = arg ran first.
shallow vs deep copy
Shallow copies the outer container only; copy.deepcopy copies nested objects too.
reference counting
CPython frees an object as soon as no references remain; a cyclic GC handles reference cycles.