Comet bursts into the maker space with her sketch notebook open. "Pip is ready to carry samples," she says. "But my planning code is acting strange."
"I made a list called spots, then wrote route = spots. I added S03 to route, and now spots has S03 too!"
Wren taps his clipboard. "What does the evidence say?" he asks. "Did you make two lists, or two names?"
Nova hovers over the desk and projects two name tags, each with an arrow. "How can I help?" she asks. "Follow each arrow and see where it lands."
Comet turns to you. "You are our lead programmer. Is it one list or two? Trace it before we run it."
In Python, a name refers to an object. When you write route = spots, Python does not copy the list.
Both names now refer to one list. This is called aliasing. A change made through one name shows through the other, because there is only one list.
# alias_list.py
spots = ["S01", "S02"]
route = spots
route.append("S03")
print(spots)
print(route)
print(route is spots) ['S01', 'S02', 'S03'] ['S01', 'S02', 'S03'] True
== checks whether two values are equal. is checks identity: whether two names refer to the very same object.
In the shell below, x and y hold equal values, but they are two separate lists.
>>> x = [42, 18] >>> y = [42, 18] >>> x == y True >>> x is y False >>> z = x >>> z is x True
| Statement | True or false? |
|---|---|
| y = x makes a copy of the list x. | ? |
| After z = x, the test z is x gives True. | ? |
| Two lists with equal values are always the same object. | ? |
| == compares values, and is compares identity. | ? |
Objects work the same way. b = a gives one Sample a second name.
Calling Sample(...) again makes a brand new object, even when its values are equal to another one.
# alias_sample.py
from sample import Sample
a = Sample("S01", "basalt", 42, 0, 2)
b = a
c = Sample("S01", "basalt", 42, 0, 2)
b.grams = 40
print(a.describe())
print(c.describe())
print(a is b)
print(a is c)
print(a.label == c.label) S01 basalt 40 g at (0, 2) S01 basalt 42 g at (0, 2) True False True
Great tracing. Tomorrow you will hand objects to functions and predict what changes.