A single definition from which half of what Python calls gotchas can be derived. Absorb it fully and you will never have to memorize those gotchas again.
Four snippets. Before opening the answer, state what each one prints and commit to the wording: not “something weird”, but a concrete output and a reason. The place where your prediction diverges from reality is the most valuable thing on this page.
def add(item, target=[]):
target.append(item)
return target
print(add(1))
print(add(2))
[1]
[1, 2]The second call appends to the same list. Not to a new one.a = [1, 2]
b = a
b += [3]
print(a)
x = 1
y = x
y += 1
print(x)
[1, 2, 3]
1One and the same += operator, two different outcomes.grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]One cell was changed — three changed.t = ([1], 2)
t[0] += [9]
print(t)
TypeError: 'tuple' object does not support item assignment
…and yet t is now ([1, 9], 2). The exception was raised, but the mutation happened.
Let us start with the definition, not with examples. In Python there is one, and it goes like this:
A value is always an object on the heap. An object has a type, contents and an address.
A name is not a container but a binding. An entry in a namespace that points to an object.
Assignment does not copy the object. It redirects the name.
Everything else on this page is a consequence. Let us check that literally: each snippet above comes out of the definition in two or three steps.
b = a does not create a list. It creates a second binding to the same object. So any change to the object is visible through both names — this is not a side effect but literally what the definition says.
Snippet C is the same thing, only there are three names instead of two, and they are anonymous. The * operator on a list repeats the elements, and the element here is a reference to the inner list. The outer list gets three references to one object.
+= is not a single operationSnippet B looks like a contradiction: one operator, different behaviour. There is no contradiction, because += is not elementary. It asks the object whether it knows how to change in place:
__iadd__, that is what gets called: the object mutates and the name stays bound to it;a + b is computed, a new object is created, and the name is rebound to it.A list has __iadd__. An int does not and cannot: integers are immutable. Hence y += 1 leaves x untouched — not because “numbers are copied”, but because y simply came to point at another object.
Snippet D is the same mechanism taken to the point of absurdity, and it clears everything up at once. t[0] += [9] unfolds into two operations: first t[0].__iadd__([9]) — the list mutates successfully; then t[0] = result — and this is where the tuple refuses. The mutation has already happened, the assignment failed. One line, two actions, and they make sense only through the definition.
def is an executable statementA function is an object just like a list. The def line is not a declaration: it executes, creates a function object and binds a name to it. So the expressions in the parameter list are evaluated at that moment — once, when the function is created, not on every call.
The computed values are stored in an attribute of the function object. You can look at them by hand:
print(add.__defaults__)
# → ([1, 2],)
Snippet A stops being a trap. The list was created once and lives in add.__defaults__; every call without the argument gets that one. This is exactly what should happen if def executes and a name is a binding.
is and == answer different questionsSince a value is an object with an address, two different questions arise: “is this the same object?” and “are these objects equal?”. The first is is, the second is ==. They are not interchangeable and coincide only by accident.
The famous a = 256; b = 256; a is b → True, with False for 257, is not a property of the language. It is two different implementation mechanisms: the cache of small integers from −5 to 256 🔧 and the folding of identical constants inside one code object. That is why in a script a = 257; b = 257 on one line gives True, while the same two lines typed separately in the REPL give False. The right answer to such a question is neither “True” nor “False” but “the question is ill-posed”.
Copying is shallow by default — it could not be otherwise: copy has to copy the object, and its contents are references. If you want a copy of the graph you need deepcopy, which carries along a dictionary of already-copied objects so as not to loop forever.
And the most expensive consequence: since every number is a full object with a header, a million numbers is a million objects plus an array of pointers to them. Numpy exists not because “C is faster”. It exists because it puts a million numbers into one contiguous buffer with no objects at all. That is not an optimization of the same thing — it is an opt-out from the R1 model inside the array.
“A namespace is a dictionary” is not true everywhere. A function's local variables live not in a dictionary but in an array of frame slots; the compiler knows them by index and emits LOAD_FAST. Inside a function locals() assembles a snapshot rather than handing out the real storage — and writing into that snapshot changes nothing 🔧. The “name → object” part remains true; what is a dictionary is the global and module namespace, and the __dict__ of an ordinary object.
“Immutable” is about the object itself, not about what is reachable from it. A tuple guarantees that its cells will not change and promises nothing about the objects in those cells. Hence snippet D, and hence the fact that a tuple with a list inside is unhashable.
An object's identity is not its address. In CPython id() returns the address 🔧, but the language promises only uniqueness for the lifetime of the object. Addresses are reused: the id of a dead object may go to a new one.
Behind all of this stands one decision: a single object model with no primitives. Python does not have two categories of values — “simple” ones and “real objects”. A number, a function, a class, a module and the type itself are objects of one kind, under the same rules.
The decision was inherited from ABC, the language Guido worked on before Python, and strengthened on purpose: one set of rules instead of two. The price is known and paid — a header on every number, an indirection on every access, no way to pack an array of numbers densely into the CPU cache. The benefit is known too: there is no “is this a value or an object” question, no autoboxing, no two kinds of equality, and any entity can be put into a list, passed to a function and given an attribute.
If you have worked with numpy, the intuition is already there — just under a different name. b = a for an array and b = a[:] as a view: two names for the same data, and a write through either is visible through both. The only difference is that numpy made you learn this explicitly (.copy() versus a view), while Python assumes you got it from the definition of the language.
The most precise analogy is std::shared_ptr without pointer arithmetic: a name owns the object, a copy of the name adds an owner, and the object lives as long as there is at least one. This analogy will come in handy again in R3: it explains not only assignment but also the moment of destruction.
Questions that come up on their own if you read closely. The answer is under the question.
is sometimes work for identical strings and numbers, and sometimes not?Because the question is not about is but about how many objects the compiler created. The operator always honestly compares identity; what varies is whether it is looking at one object or two.
Two different mechanisms create the false impression that “small values are compared by value”. The first is the small-integer cache: the numbers from −5 to 256 are created at startup and reused. The second is constant folding: identical literals inside one code object are placed into co_consts by the compiler once.
def f():
a = "hello"
b = "hello"
return a is b
print(f()) # → True one constant for the whole function
x = "hel"
print(x + "lo" is "hello") # → False the string is built at runtime
Both mechanisms are a 🔧 implementation detail, and the boundaries of both have moved between versions. The rule has no exceptions: is only for None, True, False and your own sentinel singletons. For everything else, ==.
If you want a guarantee that string objects coincide, it exists and is called sys.intern. Lesson 02 shows that on a million repeated strings it gives 21.2 → 2.6 MB.
y = x; y += 1 not change x?Because += is not one operation but a question to the object: “can you change in place?”
The interpreter calls __iadd__ if it exists and __add__ if it does not. Then — and this is the key part — the result is assigned back to the name on the left. For an immutable number there is no __iadd__, a new object is created, and the name y is rebound to it. The name x was not touched; it looks where it looked before.
x = [1]; y = x
y += [2]
print(x) # → [1, 2] the list was changed in place
x = 1; y = x
y += 1
print(x) # → 1 a number is immutable, y was rebound
Hence a non-obvious consequence: y += [2] and y = y + [2] are different operations. The first changes the object and is visible through every other name; the second creates a new one and is visible nowhere. For numbers they are indistinguishable, for lists they are not, and people get caught by this regularly.
Because the thing to fix would be not the trap but the rule itself — and the rule is right.
The default is evaluated once, when def executes, because def is an executable statement that creates a function object. Default values are stored in that object's __defaults__. The alternative — evaluating the expression on every call — would mean that def f(x=expensive()) pays for expensive() on every call, and def f(x=SOME_CONST) would stop seeing the value as of definition time.
def f(x=[]): x.append(1); return x
print(f.__defaults__) # → ([],) the object exists and lives with the function
f(); f()
print(f.__defaults__) # → ([1, 1],)
Then R9 comes into play: too much code relies on the current behaviour, including the idiom of caching through a default and the early-binding trick def f(_cache={}). So the language was left alone and the problem was worked around locally — dataclass simply forbids a mutable default and requires field(default_factory=list).
The right conclusion is not “beware of a list in a default” but “a default is an object that lives as long as the function does”. From that, the trap is derived rather than memorized.
copy.deepcopy so slow, and when is it needed at all?Because it has to solve an object-graph isomorphism problem, not just copy bytes.
deepcopy walks the whole reachable graph, keeps a dictionary of already-copied objects keyed by id (otherwise a cyclic structure would send it into a loop), and for each type looks for a suitable way to copy — __deepcopy__, __reduce_ex__, the pickle protocol. It is an interpreted traversal with dispatch at every node.
The practical conclusion: if the structure is serializable, a round trip through serialization is usually faster than calling deepcopy — because the serializer is written in C. But check with a measurement on your own data: pickle has overhead of its own, and on small objects it loses.
When deepcopy is really needed: when the structure has shared sub-objects and their sharing has to be preserved in the copy — deepcopy guarantees that, a round trip through JSON does not. When there is no sharing, it is usually enough to work out exactly which levels are mutable and copy only those.
Lib/copy.py is forty lines worth reading in full: both the memo dictionary and the dispatch table are visible there.
def executes once), the differing behaviour of += (the __iadd__ protocol, not an operator), the tripled row in [[0]*3]*3 (references are repeated), the simultaneous mutation and TypeError in a tuple (two operations on one line), and the difference between is and == (identity versus equality). None of this needs memorizing — all of it is recomputed from the definition in a couple of steps. The price of the decision is a header on every number, and that is exactly why numpy exists.
Java chose two sets of rules — int and Integer — and got autoboxing. And with it exactly the same trap: Integer a = 127, b = 127; a == b gives true, and for 128 it gives false. The same cache, the same confusion of identity and equality, only with two types instead of one and a NullPointerException on unboxing on top. Python paid with performance, Java paid with the complexity of the rules — and that did not save it from the problem.
C++ chose value semantics: assignment copies, aliasing requires an explicit reference. There are no shared-state traps; in their place are the cost of copying, copy constructors, move semantics and dangling references.
Both alternatives have been carried out and both are alive. This is not “Python got it wrong” — it is a chosen point on a real trade-off.
The function makes a defensive copy of its input. The copy is there, the reviewer sees it, the defect remains.
def mark_processed(items):
items = items[:] # defensive copy, so as not to damage the input
for item in items:
item["status"] = "done"
item["processed_at"] = now()
return items
The calling code passed in its list, got a new one back — and found that its own dictionaries had changed:
orig = [{"id": 1, "status": "new"}]
mark_processed(orig)
print(orig)
# → [{'id': 1, 'status': 'done', 'processed_at': ...}]
From consequence 1 this is visible at once: items[:] creates a new list but puts the same references into it. The copy protects against append and remove and against nothing inside the elements. Review lets it through because the protection is formally present — eyes look for its absence, not for its depth.
What makes it especially nasty is that the bug does not show up here. The calling code goes on working with “its” list, sees the statuses that were set, and concludes that the record has already been processed. The investigation will start a week later and in another module.
The cure is either an honest copy.deepcopy (expensive but unambiguous) or a function that does not mutate its input at all and builds new dictionaries. The second is almost always better — and removes the question of copy depth along the way.
Everyone knows that concatenating strings in a loop is quadratic. Yet a microbenchmark often says the opposite, and here is why.
CPython has an optimization: if a string has exactly one reference, then on s += part the interpreter extends the buffer in place instead of creating a new string. The loop then behaves linearly and looks fast. The optimization holds exactly as long as there is one reference 🔧:
def cat(n): # the string's reference count is one
s = ""
for _ in range(n):
s += "x" # CPython extends the buffer in place
return s
def cat_held(n): # two are looking at the string
s = ""
prev = None
for _ in range(n):
prev = s # a second reference — and the optimization switches off
s += "x" # now every step is a new string
return s
| variant | 20,000 concatenations × 20 |
|---|---|
| one reference to the string | 0.019 s |
| a second reference appeared | 0.061 s |
The same code, a threefold difference — caused by the innocent line prev = s, which anyone might add in a refactoring. In real code the second reference comes from logging, from passing the string to a function, from keeping an intermediate value. The optimization disappears silently.
The conclusion is not “write join because that is the convention”. The conclusion is that performance here depends on the number of references to an object, that is, on a property you cannot see in the line of code. "".join(parts) does not rely on the reference count and is therefore predictable — and predictability is worth more here than a factor of three.
Open a REPL and run the four snippets again — this time checking not against the answer but against your prediction from the first section. They diverge only where the model was wrong; agreement proves nothing, divergence proves everything.
Then finish off three questions whose answers follow from the mechanism but are not given in the text:
def f(x, cache={}):
cache[x] = True
return len(cache)
# How do you reset cache from outside the function in one line?
a = [[0] * 3 for _ in range(3)]
a[0][0] = 1
# Why is there no snippet C effect here?
t = ([1], 2)
t[0].append(9)
# Why does this work without any TypeError?
dataclasses is the only place in the standard library where the language admitted that consequence 3 is a mistake and forbade it:
from dataclasses import dataclass
@dataclass
class C:
items: list = []
# → ValueError: mutable default <class 'list'> for field items is not allowed:
# → use default_factory
Look into Lib/dataclasses.py and find this check: it tests whether the default is an instance of list, dict or set. Notice what exactly was done there — the behaviour of the language was not fixed; a guard rail was added on top of it. The mechanism itself cannot be changed: all existing code stands on it. This is the first encounter with R9, and from here on you will meet it all the time.
Lib/copy.py is forty lines worth reading in full. Pay attention to the memo dictionary in deepcopy: it exists because an object graph can contain cycles, and cycles are a direct consequence of references freely forming an arbitrary graph.
From L1 you know that every value is an object. Here: what that costs, with numbers.
Every object has a header: a reference count and a pointer to the type. On a 64-bit build that is 16 bytes before any contents. Variable-length objects add a size field — 24 bytes.
import sys
print((sys.getsizeof(0), sys.getsizeof(1), sys.getsizeof(2**70)))
# → (28, 28, 36)
print(sys.getsizeof([]))
# → 56
print(sys.getsizeof([None] * 1_000_000))
# → 8000056
An integer is not a machine word. It is an arbitrary-precision number: an array of 30-bit “digits” in 32-bit words plus a header, hence 28 bytes for one and 36 for 2**70, which already needs three digits 🔧.
Now add it up: list(range(1_000_000)) is 8 MB of pointers plus a million objects of 28 bytes each. About 36 MB where numpy.arange(1_000_000) takes 8 MB in one contiguous block, and 4 MB with dtype=int32. The difference is not in the speed of the language but in the number of objects.
The reference count can be read from Python itself — the header starts at the object's address:
import ctypes
x = [1, 2, 3]
y = x
print(ctypes.c_ssize_t.from_address(id(x)).value)
# → 2
Two — x and y. Delete one name and look again; add a third — same thing. An object's header is readable straight from Python, with no C at all, and this technique will be the main tool throughout R3.
Tag v3.11.15. Everything listed is a couple of dozen lines and can be read in one sitting.
Include/object.h — the PyObject_HEAD and PyObject_VAR_HEAD macros. Here they are, those very 16 and 24 bytes.Objects/longobject.c — the representation of an integer. Look for _PyLong_New and the handling of ob_digit.Python/ceval.c — the STORE_FAST and LOAD_FAST instructions. You can see that a local variable is an index into an array, not a key in a dictionary.Objects/listobject.c, function list_inplace_concat — the list's implementation of __iadd__, that is, literally consequence 2.copy documentation — the write-up above is enough; go to the documentation only if you need __deepcopy__.