Python References and Copying
What you will learn
- Why
b = adoes not copy a list - How to make a copy:
copy(), slicing,list() - The difference between a shallow and a deep copy
- The
[[0] * 2] * 3trap - How functions share mutable values
This lesson builds on lesson 2.6 (mutable and immutable values). Lists and dictionaries get their own chapters later; here you only need to know what they are.
1. Names are labels
In Python a variable is a label attached to a value, not a box that contains it (lesson 2.1). When you write b = a, you attach a second label to the same value. Nothing is copied.
a = [1, 2]
b = a
b.append(3)
print(a, b, a is b)
Output:
[1, 2, 3] [1, 2, 3] True
Changing the list through b also changed what a shows, because they are the same list. This is called aliasing. For immutable values (numbers, text, tuples) it never causes surprises, because they cannot change in place. For mutable values (lists, dictionaries, sets) it can.
Quick check: after `a = [1]`, `b = a`, `b.append(2)`, what is `a`?
[1, 2]. Both names point to the same list.
2. Making a real copy
To get an independent list, copy it. There are three common ways:
a = [1, 2, 3]
c = a.copy()
d = a[:]
e = list(a)
c.append(4)
print(a, c)
print(d == a, d is a, e is a)
[1, 2, 3] [1, 2, 3, 4]
True False False
| Way | Meaning |
|---|---|
a.copy() |
the list's own copy method |
a[:] |
a slice of everything (chapter 7) |
list(a) |
build a new list from the old one |
Each gives a new list with equal items (d == a is True) that is not the same object (d is a is False). Changing the copy no longer affects a. Dictionaries and sets have .copy() too.
3. Shallow and deep copies
A copy made this way is shallow: it copies the outer list, but the items inside are shared. That matters when the items are themselves mutable:
grid = [[1, 2], [3, 4]]
shallow = grid.copy()
shallow[0].append(99)
print(grid)
[[1, 2, 99], [3, 4]]
The outer list was copied, but both lists share the same inner list [1, 2]. Changing it through shallow changed grid.
A deep copy copies everything, all the way down. Use deepcopy from the copy module (importing is covered in chapter 16):
import copy
grid = [[1, 2], [3, 4]]
deep = copy.deepcopy(grid)
deep[1].append(7)
print(grid, deep)
[[1, 2], [3, 4]] [[1, 2], [3, 4, 7]]
Now grid stayed the same.
| Copy | Outer container | Inner mutable items |
|---|---|---|
b = a |
same | same |
shallow (a.copy(), a[:], list(a), copy.copy(a)) |
new | shared |
deep (copy.deepcopy(a)) |
new | new |
If a list holds only numbers or text, a shallow copy is enough. If it holds other lists or dictionaries and you plan to change them, use a deep copy.
4. The [[0] * 2] * 3 trap
Making a table by repeating a row looks tidy but shares the row:
rows = [[0] * 2] * 3
rows[0][0] = 1
print(rows)
[[1, 0], [1, 0], [1, 0]]
* 3 repeated the same inner list three times, so changing one row changed all of them. Build separate rows instead:
rows2 = [[0] * 2 for _ in range(3)]
rows2[0][0] = 1
print(rows2)
[[1, 0], [0, 0], [0, 0]]
The second form makes a new inner list for each row. It uses a list comprehension, which chapter 12 explains: for now, remember the idea, not the syntax.
5. Functions share mutable values
When you pass a value to a function, the function receives a new label to the same object. So a function can change a mutable argument for the caller:
def add_item(items):
items.append("x")
def rebind(items):
items = ["new"]
data = ["a"]
add_item(data)
print(data)
rebind(data)
print(data)
['a', 'x']
['a', 'x']
add_itemchanged the object (append), sodatachanged.rebindonly moved its own label to a new list; the caller'sdatais untouched.
Functions are the topic of chapter 11. The rule for now: changing a mutable argument is visible outside; reassigning the parameter name is not.
6. Dictionaries behave the same way
import copy
d1 = {"k": [1]}
d2 = d1
d2["k"].append(2)
print(d1)
d3 = dict(d1)
d3["z"] = 1
print(d1, d3)
d4 = copy.copy(d1)
d4["k"].append(3)
print(d1)
{'k': [1, 2]}
{'k': [1, 2]} {'k': [1, 2], 'z': 1}
{'k': [1, 2, 3]}
d2 = d1is the same dictionary.dict(d1)made a new dictionary, so adding"z"did not touchd1.- But
d1andd4share the inner list[1, 2], so appending3throughd4changedd1. That is a shallow copy again.
Worked example: two shopping lists
Rina has a list. Her brother wants a copy to add to, without changing hers.
rina = ["rice", "salt"]
brother = rina.copy()
brother.append("oil")
print(rina)
print(brother)
['rice', 'salt']
['rice', 'salt', 'oil']
| Step | What happens |
|---|---|
| 1 | rina is a list of two items |
| 2 | rina.copy() makes a new list with equal items |
| 3 | brother.append("oil") changes only the new list |
With brother = rina instead, both lists would end with oil. The items are text (immutable), so a shallow copy is enough here.
Common mistakes
- Thinking
b = amakes a copy. It makes a second name for the same object. - Using a shallow copy for nested data and changing the inner items.
- Building a table with
[[0] * 2] * 3. Use a separate list for each row. - Changing a list inside a function and being surprised that the caller's list changed.
- Forgetting
import copybefore usingcopy.deepcopy.
Key takeaways
b = agives one object two names. For lists, dictionaries and sets that means a change through one name shows through the other.- Make an independent copy with
.copy(),[:]orlist(...). - Those are shallow copies: inner mutable items are still shared. Use
copy.deepcopyfor full independence. [[0] * 2] * 3repeats one inner list; build separate rows instead.- A function can change a mutable argument for its caller, but reassigning the parameter name does not.
Practice
1. a = [1, 2], b = a, b[0] = 9. What is a?
Show answer
[9, 2]. Both names point to the same list.
2. Write one line that makes c an independent copy of the list a, and one line to test that they are different objects.
Show answer
c = a.copy() (or c = list(a)), then c is a, which gives False.
3. m = [[1], [2]] and n = m.copy(), then n[0].append(5). What is m? Why?
Show answer
[[1, 5], [2]]. The copy is shallow, so m and n share the inner lists.
4. How would you make n fully independent in question 3?
Show answer
import copy, then n = copy.deepcopy(m).
5. What is the problem with table = [[0] * 3] * 2? How do you fix it?
Show answer
Both rows are the same list, so changing one changes both. Use table = [[0] * 3 for _ in range(2)] so that each row is a new list.
6. A function does numbers.append(1) on its parameter. Does the caller's list change? What if it does numbers = [1] instead?
Show answer
With append, yes: the same list is changed. With numbers = [1], no: that only moves the function's own name to a new list.