LESSON 1.01 · 6 STAGES · 3 CONTROLS · 3 CHECKS
Names, objects and mutability
Watch two names share one object, and see which changes show through.
EXPLAINER · 1.01 · OBJECT BAY
01
Stage 1 of 6 · Bind a name
The name a points to a new mutable list object with an id.
Explain it simply
Python makes a list in memory. That's an object: a box with a type, an id and a value. The name a is like a sticky note on the box. The note points to the box. It isn't the box itself.
The name a points to a list object with id 2208. Its value is [1, 2, [3, 4]].
nameobject and valueid and referencenew item, resultshared mutable object
Toy: 3 names · up to 5 objects · a 6-line program · ids are short stand-ins for addresses
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
list
Pick the type of the first object.
+=
In-place form or new-object form.
copy.copy
One level or every level.
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
The name a points to one object with a type, an id and a value.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import copy
a = [1, 2, [3, 4]] # a names a new list
b = a # a second name for the same object
b += [5] # changes the object in place: a sees it
c = copy.copy(a) # one level only: the inner list stays shared
print(a, b, c) # [1, 2, [3, 4], 5] [1, 2, [3, 4], 5] [1, 2, [3, 4], 5]
print(id(a) == id(b)) # True
print(a == c) # True
print(a is c) # False
print(a[2] is c[2]) # True
Copy it into a file or a Python shell and run it. Your ids will be different numbers; the True and False results will match.
Common mix-ups
MYTHb = a makes a copy of the list.
FIXAssignment binds a second name to the same object. A change through b shows through a.
MYTHcopy.copy copies the inner list too.
FIXcopy.copy copies the outer list only. The inner list stays shared. copy.deepcopy copies every level.
Predict, then reveal
0 / 3 REVEALEDQ01With a tuple, does b += (5,) change what a shows?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02With a list, does b = b + [5] change what a shows?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03After copy.deepcopy, is a[2] is c[2] True or False?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Takeaways
- A name points to an object; assignment never copies it.
- A change to a mutable object shows through every name for it.
- == compares values; is compares ids.