Kodewick
Start learning →
Names and objects: references, aliases and copies5 / 52

Names and objects: references, aliases and copies

Lesson 5 of 52 · Part 2 · Names, lists and linked lists · about 17 minutes

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

a
b

Objects

[1, 2, 3]list

b = a copies nothing, b just points at the same list; b.append(4) changes that one object, so a sees the 4 too
main.py
1a = [1, 2, 3]2b = a3b.append(4)4print(a)5print(b)6print(a is b)
Output
[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.

Guess the outputA wrong guess is fine

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)

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.

main.py
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))
Output
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.)

WrittenAsksUsually for
x == yequal values?numbers, strings, the contents of lists
x is ythe same object?x is None, checking whether two names are aliases
id(x) == id(y)the same, spelled outdebugging 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.

Guess the outputA wrong guess is fine

After b = b + [4], what does it print?

1a = [1, 2, 3]2b = a3b = b + [4]4print(a, a is b)
Choose allPick all that apply

How can you check whether a and b are the same object (not just equal values)? You can pick more than one.

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

a
b

Objects

[1, 2]list
[9, 2, 5]list

a and b start on the same list: b[0] = 9 changes it in place, so a sees it; b = b + [5] makes a new object, and from then on a and b go separate ways

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].

main.py
1a = [1, 2]2b = a3b += [3]4print(a)5b = b + [4]6print(a, b)
Output
[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.

main.py
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)
Output
[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.

Choose one

a and b point at the same list. Which line does the same as b += [5]?

Guess the outputA wrong guess is fine

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)
Exercise 1

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.

It should print
[1, 2, 3]
[3, 1, 2]
False
exercise1.py
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)
Output
Press Run or Ctrl+Enter

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

[0, 0, 0]list

board = [[0] * 3] * 3: the outer list's three cells all point at one [0, 0, 0], so changing board[0][0] changes that one row
main.py
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])
Output
[[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.
main.py
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])
Output
[[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.

WrittenOuter listObjects insideCost
b = athe samethe sameO(1), one more label
a[:], a.copy(), list(a)newthe sameO(n), n references copied
copy.deepcopy(a)newall newin 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.

Guess the outputA wrong guess is fine

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)
Exercise 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.

It should print
[[0, 7, 0], [0, 0, 0]]
False
exercise2.py
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])
Output
Press Run or Ctrl+Enter

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:

main.py
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"))
Output
['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 =None and 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)
a.next = b just makes the next of node a point at the object b; c = a.next gets b itself
Guess the outputA wrong guess is fine

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", []))

Summary

Take-away

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)]