← All lessons
Python advanced · Lesson 2 of 11

Names, objects and copies

In the basics course a variable was a box holding a value. The truer picture is a label: every value is an object living somewhere in memory, and a variable is a name pointing at one. b = a doesn't copy anything; it sticks a second label on the same object. With immutable objects like numbers and strings you can't tell the difference. With mutable ones you can:

a = [1, 2, 3]
b = a
b.append(4)
print(a)
Prints
[1, 2, 3, 4]

Both names point at one list, so a change through either name shows through both. Compare that with rebinding, pointing a name at a different object, which never affects other names:

a = [1, 2, 3]
b = a
b = b + [4]
print(a, b)
Prints
[1, 2, 3] [1, 2, 3, 4]

b + [4] makes a new list and b = moves the label to it. So b.append(4) (mutates) and b = b + [4] (rebinds) look similar but mean different things. == asks whether two objects have equal values; is asks whether they're the very same object. Use is only for None (if x is None:), and == for everything else.

x = [1, 2]
y = [1, 2]
z = x
print(x == y, x is y, x is z)
Prints
True False True

To get an independent copy, ask for one: items.copy(), list(items) or items[:] for a list, d.copy() for a dict. These are shallow copies: a new outer container, but the items inside are shared. If the items are themselves mutable (a list of lists), use copy.deepcopy(), which copies all the way down.

import copy

grid = [[0, 0], [0, 0]]
shallow = grid.copy()
deep = copy.deepcopy(grid)
grid[0][0] = 9
print(shallow[0][0], deep[0][0])
Prints
9 0

The same rule explains a classic surprise: [[0] * 3] * 3 makes a list of three labels on one inner list, so changing one row changes them all. Write [[0] * 3 for _ in range(3)] instead, which makes three separate rows.

Function arguments work the same way: the parameter becomes another name for the caller's object. A function that mutates a list it was given changes the caller's list; a function that rebinds its parameter doesn't. That's why functions that change their arguments should say so, and why many good functions return a new value instead.

def add_item(items, x):
    items.append(x)

def replace(items):
    items = ["new"]

basket = ["egg"]
add_item(basket, "milk")
replace(basket)
print(basket)
Prints
['egg', 'milk']

Practice

What does this print?

a = {"x": 1}
b = a
b["x"] = 2
print(a["x"])
More info

Quick reference

name → objectVariables are labels on objects; b = a adds a label, it doesn't copy.
mutate vs rebindx.append(1) changes the object; x = ... points the name elsewhere.
== / isEqual values / the same object. Use is for None only.
copy() / copy.deepcopy()Shallow copy (inner items shared) / full copy.
[[0] * n for _ in range(m)]A grid with separate rows.

Related courses