Skip to content

Volume ITechnology

3.13.2 — Names, Objects & Mutability ​

A shopping-cart service has a bug report. A customer added a notebook to their saved-for-later list, and the notebook also appeared in their cart. Nobody wrote code that touches the cart. The cause is one line, saved = cart, written months ago, and the reason it causes the bug is the most important idea in Python: a variable is not a box that holds a value. It is a label stuck onto an object. This page builds that idea from the bottom up, because nearly every confusing Python bug comes from forgetting it.

1. Everything is an object ​

In Python, every value is an object. A number is an object. A string is an object. A list, a function, a class, a module, even None, are all objects. There are no "primitive" values living outside the object system, as int does in Java or as numbers do in JavaScript's engine (3.6.9).

Every object has three things.

  1. An identity. This is a number that never changes while the object is alive. In CPython it is simply the object's address in memory. You read it with id(obj).
  2. A type. The type decides what the object can do: which operations work on it and which methods it has. You read it with type(obj). The type never changes either.
  3. A value. This is the data the object holds. For some objects the value can change. For others it cannot. That difference is the whole of section 4.
python
cart = ["mug", "pen"]

print(id(cart))              # (1)
print(type(cart))            # (2)
print(type(type(cart)))      # (3)
text
2269012463360
<class 'list'>
<class 'type'>
  • (1) The identity. Your number will differ, because it is a memory address.
  • (2) The type of the object is list.
  • (3) The type is itself an object, and its type is type. Classes are objects too. 3.13.7 follows that thread all the way down.

What an object looks like in memory ​

Under the hood, every CPython object starts with the same small header. It is a C structure called PyObject, and on a 64-bit machine it holds two fields of 8 bytes each.

  • A reference count. This is the number of places that currently point at the object. When it reaches zero, CPython frees the object immediately. 3.13.13 explains it fully.
  • A pointer to the object's type. That is how type(obj) works, and how the interpreter finds the right code to run for + or len().

After the header comes the object's own data. That is why even tiny values are not tiny.

python
import sys

print(sys.getsizeof(1))          # (1)
print(sys.getsizeof(2 ** 100))   # (2)
print(sys.getsizeof(1.5))        # (3)
print(sys.getsizeof(None))       # (4)
print(sys.getsizeof([]))         # (5)
text
28
40
24
16
56
  • (1) The number 1 takes 28 bytes: 16 for the header, 8 recording how many "digits" the number has, and 4 for the one digit. A C int takes 4 bytes.
  • (2) Python integers can grow without limit, so a huge number simply uses more digits. 3.13.3 shows how.
  • (3) A float is the header plus one 8-byte floating-point number.
  • (4) None is the bare header and nothing else.
  • (5) An empty list already costs 56 bytes, before it holds anything.

This is the main reason a Python list of one million numbers uses far more memory than a C array of one million numbers. The list holds a million pointers, and each pointer leads to a separate 28-byte object. It is also why NumPy exists: a NumPy array stores raw numbers packed side by side, as C does.

2. Names are labels, not boxes ​

Now the central idea. When you write cart = ["mug", "pen"], Python does two things.

  1. It creates a list object somewhere in memory.
  2. It makes the name cart point at that object.

The name does not contain the list. It is attached to it, the way a luggage tag is attached to a suitcase. This kind of statement is called binding a name to an object. Now look at the bug from the opening.

python
cart = ["mug", "pen"]
saved = cart                       # (1)
saved.append("notebook")           # (2)

print(cart)                        # (3)
print(saved is cart)               # (4)
text
['mug', 'pen', 'notebook']
True
  • (1) Assignment never copies an object. It only sticks a second label, saved, onto the same list.
  • (2) append changes the list object itself.
  • (3) So cart sees the change. There was only ever one list.
  • (4) is asks "are these two names attached to the same object?" The answer is yes.

Figure 1 shows the situation in memory after line (2).

namescartsavedone list objectrefcount: 2 · type: listslot 0slot 1slot 2str objects"mug""pen""notebook"
Figure 1 — Names point at objects. cart and saved are two labels on one list. The list itself does not hold the strings either. Each slot holds a pointer to a separate string object.

Look at the right half of the figure too. Even the list does not contain its strings. Each slot holds a pointer to a separate string object. References all the way down is the shape of every Python data structure.

is versus == ​

Python has two ways to compare, and they ask different questions.

  • a == b asks: do these two objects have equal values? The type decides what "equal" means, through a method called __eq__ (3.13.6).
  • a is b asks: are these the very same object? It compares identities. No method is called and it cannot be customised.
python
first_order = ["mug", "pen"]
second_order = ["mug", "pen"]

print(first_order == second_order)   # (1)
print(first_order is second_order)   # (2)
text
True
False
  • (1) Same contents, so equal values.
  • (2) Two separate list objects, so not the same object.

The rule of thumb is simple. Use == to compare values. Use is only to check for singletons, which are objects that exist exactly once, like None, True and False. Writing if result is None: is correct and is the style the Python community expects. Writing if count is 5: is a bug that happens to work sometimes, and the next section explains why it only works sometimes.

The small-integer cache and string interning ​

Creating a new object for every number would be wasteful, because programs use small numbers constantly. So CPython creates the integers from −5 to 256 once, at startup, and reuses them forever. This is the small-integer cache.

python
a = 256
b = 256
print(a is b)              # (1)

x = int("257")
y = int("257")
print(x is y, x == y)      # (2)
text
True
False True
  • (1) Both names point at the one cached 256 object.
  • (2) 257 is outside the cache, so each int() call builds a new object. Equal values, different objects.

Strings get a similar treatment called interning. Strings that look like identifiers, such as "order_id", are often stored once and shared, because Python itself uses them constantly as variable and attribute names. You can force it with sys.intern().

python
import sys

key = "order_id"
built = "".join(["order", "_id"])     # (1)

print(built == key, built is key)     # (2)
print(sys.intern(built) is key)       # (3)
text
True False
True
  • (1) A string built at run time is a fresh object.
  • (2) Equal value, but a different object.
  • (3) sys.intern returns the one shared copy, which is the same object as key.

Both of these are CPython implementation details, not language promises. That is exactly why is on numbers or strings is a bug. Your code works in a quick test with small numbers and fails in production with large ones.

3. How function arguments really work ​

People argue about whether Python is "pass by value" or "pass by reference". It is neither, and the label/object picture ends the argument. Python uses call by sharing, sometimes called pass by object reference. When you call a function, each parameter name becomes a new label on the same object the caller passed in.

That one rule gives you two behaviours that look contradictory but are not.

python
def add_item(items, item):
    items.append(item)          # (1)
    items = ["replaced"]        # (2)
    return items

basket = ["apple"]
result = add_item(basket, "bread")
print(basket)                   # (3)
print(result)
text
['apple', 'bread']
['replaced']
  • (1) items is a label on the caller's list. append changes that object, so the caller sees the change.
  • (2) This line does not change any object. It moves the local label items onto a brand-new list. The caller's basket label is untouched.
  • (3) So basket has the bread from line (1) but not the replacement from line (2).

Remember it this way. Changing an object is visible to everyone who holds a label to it. Re-binding a name is only visible to that one name.

Now the same idea with a number.

python
def add_shipping(total):
    total += 40          # (1)
    return total

price = 100
print(add_shipping(price), price)
text
140 100
  • (1) Integers cannot be changed. So total += 40 cannot modify the 100 object. It creates a new 140 object and re-binds the local label total to it. The caller's price still points at 100.

The function behaved differently for the list and the number, but the rule was the same both times. The difference comes from the objects: a list can be changed, and an integer cannot. That property has a name.

4. Mutable and immutable objects ​

An object is mutable if its value can change after it is created. It is immutable if it cannot.

ImmutableMutable
int, float, boollist
str, bytesdict
tuple, frozensetset, bytearray
Nonemost objects of your own classes

Every "change" to an immutable object is really the creation of a new object. When you write name = name.upper(), the old string is not altered. A new string is made, and the label moves to it.

Why immutability matters: dictionary keys ​

A dict finds a key by computing its hash, a number calculated from the key's value, and jumping straight to the matching slot. 3.13.3 shows the full mechanism. If a key's value could change after it was stored, its hash would change too, and the dict would look in the wrong slot and lose the entry forever. So Python only lets hashable objects be keys, and the built-in mutable types refuse to be hashed.

python
price_by_size = {("mug", "large"): 450}     # (1) a tuple key is fine

try:
    stock = {["mug", "large"]: 12}          # (2)
except TypeError as error:
    print("TypeError:", error)
text
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
  • (1) A tuple of strings never changes, so it can safely be a key.
  • (2) A list could change after being stored, so Python refuses to hash it.

The tuple that changes anyway ​

Here is a classic interview puzzle. A tuple is immutable, so can this tuple change?

python
order = ("ORD-7", ["mug"])
order[1].append("pen")              # (1)
print(order)

try:
    order[0] = "ORD-8"              # (2)
except TypeError as error:
    print("TypeError:", error)

try:
    hash(order)                     # (3)
except TypeError as error:
    print("TypeError:", error)
text
('ORD-7', ['mug', 'pen'])
TypeError: 'tuple' object does not support item assignment
TypeError: unhashable type: 'list'
  • (1) The tuple's second slot points at a list, and the list is mutable. We are changing the list, not the tuple. The tuple still points at the same list object it always did.
  • (2) Changing which object a slot points at is forbidden. That is what tuple immutability actually promises.
  • (3) Because it holds a mutable list, this tuple cannot be hashed and cannot be a dict key.

So "immutable" means the container's own slots can never be re-pointed. It does not mean everything reachable from it is frozen.

+= behaves differently on mutable and immutable objects ​

This one surprises experienced engineers.

python
cart = ["mug"]
same_cart = cart
cart += ["pen"]                 # (1)
print(same_cart)

tags = ("sale",)
same_tags = tags
tags += ("new",)                # (2)
print(same_tags, tags)
text
['mug', 'pen']
('sale',) ('sale', 'new')
  • (1) For a list, += calls a method named __iadd__, which changes the list in place. Both labels see it.
  • (2) A tuple has no in-place version, so += falls back to tags = tags + ("new",). That builds a new tuple and moves only the tags label.

5. Copying: shallow and deep ​

Since assignment never copies, you must ask for a copy when you want one. There are two kinds, and the difference matters as soon as objects contain other objects.

  • A shallow copy makes a new outer object, but its slots point at the same inner objects as the original.
  • A deep copy copies the outer object and, recursively, every object inside it.
python
import copy

order = {"id": 7, "lines": [{"sku": "mug", "qty": 1}]}
shallow = copy.copy(order)               # (1)
deep = copy.deepcopy(order)              # (2)

shallow["lines"][0]["qty"] = 5           # (3)
print(order["lines"][0]["qty"])
print(deep["lines"][0]["qty"])
text
5
1
  • (1) A new dict, but its "lines" slot points at the original list.
  • (2) New dict, new list, new inner dict. Nothing is shared.
  • (3) Changing the line through the shallow copy changes the original too, because they share the list. The deep copy is unaffected.

Shallow copies are everywhere, often hidden. list(x), x[:], x.copy() and dict(x) are all shallow. They are perfectly correct when the contents are immutable, like a list of strings, and wrong when the contents are mutable, like a list of dicts.

deepcopy also handles objects that point back at themselves. It keeps a record called a memo of every object it has already copied, so it never loops forever and never copies the same object twice.

The grid trap ​

The most famous form of accidental sharing is building a grid with *.

python
grid = [[0] * 3] * 3                      # (1)
grid[0][0] = 1
print(grid)

grid = [[0] * 3 for _ in range(3)]        # (2)
grid[0][0] = 1
print(grid)
text
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
  • (1) [row] * 3 makes a list holding three labels to one row. Change the row once and every "row" shows it. This is the same bug as the cart, in disguise.
  • (2) The comprehension runs [0] * 3 three separate times, so you get three separate rows. Always build nested lists this way.

6. Truthiness and None ​

Any object can be used in an if statement. Python decides whether it counts as true or false using a simple rule. An object is falsy if it is None, False, a zero of any number type, or an empty container. Everything else is truthy.

python
print(bool(0), bool(0.0), bool(""), bool([]), bool({}), bool(None))   # (1)
print(bool("0"), bool([0]), bool(" "))                                 # (2)
text
False False False False False False
True True True
  • (1) All the "nothing" values are falsy.
  • (2) A string containing the character "0" is not empty, so it is truthy. So is a list containing a zero.

Your own classes join in through two methods. Python first looks for __bool__. If there is none, it uses __len__ and treats a length of zero as false.

python
class Cart:
    def __init__(self, items):
        self.items = items

    def __len__(self):                 # (1)
        return len(self.items)

print(bool(Cart([])), bool(Cart(["mug"])))
text
False True
  • (1) Because Cart defines __len__, an empty cart is falsy. So if cart: reads naturally as "if the cart has anything in it".

This is why idiomatic Python writes if items: instead of if len(items) > 0:. But truthiness has one dangerous edge. Suppose a discount can legitimately be 0. Then if discount: treats "no discount was given" (None) and "a discount of zero" (0) the same way. When 0 or an empty string is a valid value, write if discount is not None: instead.

None itself is Python's single "no value" object. There is exactly one None in the whole program, which is why is None is the right test. Its type is NoneType. A function that ends without a return statement returns None.

7. Two last surprises, explained by the same idea ​

NaN is not equal to itself, yet in finds it. The floating-point value NaN, short for "not a number", is defined by the IEEE 754 standard to be unequal to everything, including itself.

python
missing = float("nan")
readings = [missing]

print(missing == missing)    # (1)
print(missing in readings)   # (2)
text
False
True
  • (1) By the standard, NaN is never equal to anything.
  • (2) But in checks is first and == only if that fails. The very same object is in the list, so it is found. Containers use identity as a shortcut, because an object is always assumed to equal itself.

0.1 + 0.2 == 0.3 is False. That is not a Python quirk. It is how binary floating point works in every language. 3.13.3 explains why, and how Decimal fixes it for money.

What the interviewer will push on ​

"Is Python pass-by-value or pass-by-reference?" They are checking whether you know the actual model. The good answer is call by sharing: the parameter becomes a new name bound to the same object. Mutating that object is visible to the caller. Re-binding the parameter is not. Show both with one short example. The common wrong answer is "mutable types are passed by reference and immutable types by value". The rule is the same for every type. Only the objects differ.

"What is the difference between is and ==?" Identity versus value. The tell of real understanding is mentioning why a is b is sometimes True for small integers: the small-integer cache from −5 to 256, which is a CPython detail. The memorised answer stops at "is compares memory addresses".

"Why can't a list be a dictionary key?" They want the chain of reasoning: a dict finds keys by hash, a mutable key's hash would change after it was stored, and the entry would be lost. So mutable built-ins are unhashable. Volunteer the tuple twist: a tuple that contains a list is also unhashable.

"What does this print?" (the grid or the default-argument trap) They are checking whether you can trace references, not whether you have seen the puzzle. Draw the labels. [[0] * 3] * 3 is three labels on one row. The mutable default argument trap in 3.13.4 is the same bug again.

"Shallow or deep copy?" A good answer names which built-in operations are shallow (list(x), x[:], .copy(), dict(x)) and says when that is fine: when the contents are immutable. Bonus for knowing that deepcopy uses a memo dict to handle cycles.

Something to volunteer that nobody asks for: every Python object carries a 16-byte header, a reference count and a type pointer, so the number 1 takes 28 bytes. That is why a list of a million integers uses about 36 MB (8-byte pointers plus 28-byte objects), and why NumPy, which stores raw packed numbers, is both faster and smaller.

Recall

  • Every value is an object with an identity (id), a type (type) and a value. In CPython each object starts with a header holding a reference count and a type pointer.
  • A variable is a label. Assignment binds a name to an object and never copies. saved = cart makes two labels on one list.
  • == compares values through __eq__. is compares identity and should be used for singletons like None. The small-integer cache (−5 to 256) and string interning make is seem to work on values, but they are CPython details.
  • Functions use call by sharing. Mutating an argument is visible to the caller. Re-binding the parameter is not.
  • Mutable objects (list, dict, set) can change. Immutable ones (int, str, tuple) cannot. Only hashable objects can be dict keys or set members. A tuple holding a list is still unhashable.
  • += changes a list in place but builds a new tuple. copy.copy is a shallow copy. copy.deepcopy is a deep copy that handles cycles with a memo. [[0]*3]*3 shares one row.
  • Falsy: None, False, zeros and empty containers. Classes use __bool__, then __len__. Use is not None when 0 or "" is a valid value.

Self-test: Draw the memory after a = [1, 2]; b = a; b.append(3). Why does a function that does items = [] not empty the caller's list? Why is (1, [2]) unhashable? What does [[]] * 3 give you, and how do you build three independent lists?

Quiz Bank ​

FoundationalWhat happens in memory when you write b = a for a list?

Nothing is copied. Python makes the name b point at the same list object that a already points at. There is now one list with two labels, and its reference count goes up by one. Any change made through either name, such as b.append(3), changes that single list, so both names see it. To get an independent list you must ask for a copy, for example b = a.copy() or b = list(a).

AppliedA function receives a config dict, sets config['debug'] = True for its own use, and suddenly the whole application runs in debug mode. Explain and fix.

The function received a label on the same dict the rest of the application uses, because Python passes arguments by sharing. Setting a key mutates that shared object, so every other holder of the dict sees debug = True. The fix is to copy before changing: local = {**config, "debug": True} or local = config.copy() and then change local. If the dict holds nested mutable values that the function also changes, use copy.deepcopy. A stronger design is to treat configuration as read-only, for example by using a frozen dataclass from 3.13.8.

InterviewWhy is 'if x is 300:' a bug even if it passes in your quick test?

is compares identity, not value. CPython caches the integers from −5 to 256, so for those values every 256 is the same object and is happens to work. 300 is outside the cache. Whether two 300 values are the same object depends on how they were created. Two constants in the same compiled block may be shared, but a 300 computed at run time is usually a new object. So the test may pass in a small script and fail in production. Python 3.8 and later even prints a SyntaxWarning for is with a literal. Use == for values.

StaffYour service holds a large in-memory catalogue as a list of a million small dicts and uses 900 MB. How would you reason about the memory, and what would you change?

Start from the object model. Each dict carries its own header and its own hash table, often a few hundred bytes even when small. Every string and number inside it is a separate object with its own 16-byte header, unless it is shared through interning or the small-integer cache. And the list holds a million 8-byte pointers on top. Measure first with sys.getsizeof on samples and with tracemalloc (3.13.13). Then reduce the per-item cost. Replace the dicts with a class using __slots__ or a slotted dataclass, which removes the per-object dict. Intern repeated strings such as category names. Store numeric columns in an array or NumPy array, which packs raw values. Or keep the data in SQLite and load only what each request needs. Each step attacks one of the overheads you can name.

Next: you now know that every value is an object behind a label. 3.13.3 opens up the built-in types themselves: how an int grows without limit, why a dict is fast, and what append really costs.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet