Names and objects: references, aliases and copies
A Python variable is a label stuck on an object, not a box holding a value: b = a puts two names on one list without copying, so [[0] * 3] * 3 repeats one row three times, and only a copy makes a new object.
You want a 3×3 board in Python, so you write board = [[0] * 3] * 3 and set the top-left cell to 1. Print it, and the first cell of all three rows is 1. It is not a bug. It is Python's most basic rule: a variable is a label stuck on an object, and assignment sticks on another label without copying anything. Every data structure that follows (a linked list's next, a tree's left and right, a graph's adjacency lists) is built on this rule, so it is worth seeing clearly first.
Variables are labels, not boxes
In C, int a = 5; is a box called a with 5 inside. Python works differently: a = [1, 2, 3] first makes a list object in memory, then sticks the name a on it.
b = a does not make another list. It sticks the name b on the same object. Now a and b are aliases: change the object through one name and the other sees it.
Names
abObjects
1a = [1, 2, 3]2b = a3b.append(4)4print(a)5print(b)6print(a is b)
[1, 2, 3, 4] [1, 2, 3, 4] True
a is b asks "are these two names on the same object?" Here the answer is True.
Change it through a, then look through b. What does it print?
1a = [1, 2]2b = a3a.append(3)4print(len(b), b is a)
b = a copied nothing: a and b are two names for the same list. a.append(3) changes that object, so its length seen through b is 3 too, and b is a is True.is and == are different questions
== compares values. is asks whether two names are the same object. Two lists can be equal in value and still be two different objects.
1a = [1, 2]2b = a3c = [1, 2]4print(a == c, a is c)5print(a == b, a is b)6print(id(a) == id(b), id(a) == id(c))
True False True True True False
id(x) is an object's identity number: the same object has the same number. (The number itself changes from run to run, so compare it, never print it.)
| Written | Asks | Usually for |
|---|---|---|
x == y | equal values? | numbers, strings, the contents of lists |
x is y | the same object? | x is None, checking whether two names are aliases |
id(x) == id(y) | the same, spelled out | debugging which object is which |
Always test for None with x is None: there is only one None object, and is is both the fastest and the exact test.
After b = b + [4], what does it print?
1a = [1, 2, 3]2b = a3b = b + [4]4print(a, a is b)
b + [4] first makes a new list [1, 2, 3, 4], then sticks the name b on that new object. Nobody touched the old object, a still points at it, so a is still [1, 2, 3] and a and b are no longer the same object. The next level is all about this difference.How can you check whether a and b are the same object (not just equal values)? You can pick more than one.
is asks exactly "is this the same object?", and id(a) == id(b) compares identity numbers, which means the same. a == b only compares values: two different lists with the same contents give True.Changing in place, or rebinding
There are only two things you can do through a name:
- Change the object in place:
b.append(4),b[0] = 9,b.sort(). It is still the same object, and every name pointing at it sees the change. - Rebind the name:
b = .... The label b is peeled off the old object and stuck on a new one. The old object is unchanged and other names are not affected.
Names
abObjects
One exception catches people: for a list, b += [5] changes it in place (like b.extend([5])). It is not the same as b = b + [5].
1a = [1, 2]2b = a3b += [3]4print(a)5b = b + [4]6print(a, b)
[1, 2, 3] [1, 2, 3] [1, 2, 3, 4]
Passing a list to a function follows the same rule: the parameter is just one more name on the same object. Change the object in place inside the function and the caller sees it; rebind the parameter and the caller does not.
1def add_one(nums):2 nums.append(1)3 4def replace(nums):5 nums = [0, 0]6 7data = [5]8add_one(data)9print(data)10replace(data)11print(data)
[5, 1] [5, 1]
Immutable objects such as int, str and tuple cannot be changed in place: x += 1 always makes a new object and rebinds the name, so a function cannot change a number outside it.
a and b point at the same list. Which line does the same as b += [5]?
+= changes it in place, just like b.extend([5]), so a changes too. b = b + [5] is the one that makes a new object and moves the label. This is where lists and ints are easiest to mix up: x += 1 on an integer always makes a new object.Inside the function: first +=, then a rebinding, then append. What is data outside?
1def grow(nums):2 nums += [0]3 nums = [9]4 nums.append(9)5 6data = [1]7grow(data)8print(data)
nums += [0] changes in place, so it changes the very object data names: it becomes [1, 0]. nums = [9] peels the parameter name off and sticks it on a new list, so the append(9) after that changes the new list and has nothing to do with data.Leave the caller's list alone
✓sorted_copy(nums) should return the numbers sorted without changing the list passed in. Right now it changes data outside as well. Fix it.
[1, 2, 3] [3, 1, 2] False
1def sorted_copy(nums):2 nums.sort()3 return nums4 5data = [3, 1, 2]6result = sorted_copy(data)7print(result)8print(data)9print(result is data)
Copies: shallow and deep
Back to the board. [[0] * 3] * 3 makes one [0, 0, 0], then repeats the reference to it three times. All three cells of the outer list point at the same row.
Names
board[0]board[1]board[2]Objects
1board = [[0] * 3] * 32board[0][0] = 13print(board)4print(board[0] is board[2])5 6good = [[0] * 3 for _ in range(3)]7good[0][0] = 18print(good)9print(good[0] is good[2])
[[1, 0, 0], [1, 0, 0], [1, 0, 0]] True [[1, 0, 0], [0, 0, 0], [0, 0, 0]] False
The list comprehension runs [0] * 3 once per turn, so each row is a new list of its own. [0] * 3 itself is fine: the 0s inside are immutable integers, and sharing one of them can never go wrong.
When you need "a copy of my own", be clear about how deep the copy goes:
- Shallow copy:
a[:],list(a),a.copy(),copy.copy(a). A new outer list, holding the same objects as before. - Deep copy:
copy.deepcopy(a). Layer by layer, every object inside is copied too.
1import copy2 3a = [[1, 2], [3, 4]]4shallow = a.copy()5deep = copy.deepcopy(a)6a[0].append(9)7print(shallow)8print(deep)9print(shallow is a, shallow[0] is a[0], deep[0] is a[0])
[[1, 2, 9], [3, 4]] [[1, 2], [3, 4]] False True False
The shallow copy's outer list is new (shallow is a is False), but the [1, 2] inside is the same object, so it became [1, 2, 9] as well. The deep copy is new all the way down and is not affected at all.
| Written | Outer list | Objects inside | Cost |
|---|---|---|---|
b = a | the same | the same | O(1), one more label |
a[:], a.copy(), list(a) | new | the same | O(n), n references copied |
copy.deepcopy(a) | new | all new | in proportion to every object inside |
In interviews: "What is wrong with [[0] * n] * m?", "Why should a default argument never be []?" and "Shallow copy versus deep copy" come up all the time. They all have the answer from this lesson: assignment and * copy references, not objects.
b is a shallow copy of a. Change what is inside b[0], then rebind b[1]. What does a print as?
1a = [[1], [2]]2b = a[:]3b[0].append(5)4b[1] = [7]5print(a)
b[0] and a[0] are still the same [1], so append(5) shows on both sides. b[1] = [7] just points b's second cell at a new list; a's second cell still points at the original [2].Every row its own
✓Finish make_grid(rows, cols): return a 2D list of 0s with rows rows and cols columns, where every row is an object of its own.
[[0, 7, 0], [0, 0, 0]] False
1def make_grid(rows, cols):2 # every row must be a new list3 return []4 5g = make_grid(2, 3)6g[0][1] = 77print(g)8print(g[0] is g[1])
How you write it at work
A default argument is made only once. The [] in def f(x, acc=[]) is made when the function is defined, and every call after that gets the same list:
1def add_item(item, bag=[]):2 bag.append(item)3 return bag4 5print(add_item("a"))6print(add_item("b"))7 8def add_item_ok(item, bag=None):9 if bag is None:10 bag = []11 bag.append(item)12 return bag13 14print(add_item_ok("a"))15print(add_item_ok("b"))
['a'] ['a', 'b'] ['a'] ['b']
A few everyday habits:
- For an n×m table, write
[[0] * m for _ in range(n)], never[[0] * m] * n. - So a function does not change the caller's list: start with
nums = nums[:], or return a new list. - When a default argument needs a mutable object, write
=Noneand make the object inside the function. - Test for nothing with
is None; compare contents with==.
When we write linked lists and trees, node.next = other makes the name next point at another node object: nodes are joined by exactly the references of this lesson. Press play to watch it:
class Node: def __init__(self, val): self.val = val self.next = None a = Node(1)b = Node(2)a.next = bc = a.nextprint(c is b, c.val)
The default seen=[] is made only once. What does it print?
1def tally(x, seen=[]):2 seen.append(x)3 return len(seen)4 5print(tally("a"), tally("b"), tally("c", []))
[], so its length is 1. A default is made when the function is defined, and every call that leaves it out shares that object, which is why you write seen=None.Summary
Names are labels, and assignment only sticks on labels
- b = a copies nothing: a and b are two names for one object
- is asks "the same object?", == compares values; test None with is None
- Changes in place (append, b[0] = …, +=) are seen through every name; b = … only moves b
- [[0] * 3] * 3 is one row three times; build separate rows with a comprehension
- A shallow copy is new one level down, deepcopy all the way down
- Parameters are names too: in-place changes inside a function show outside; rebinding does not
1b = a # the same object2c = a[:] # a shallow copy3d = copy.deepcopy(a)4grid = [[0] * m for _ in range(n)]