Names are not boxes
Worked examples
Read the claim, then run it and check the machine agrees. One at a time — nothing here is taken on trust.
a = [1, 2, 3]
b = a # b is a SECOND NAME for a's list, not a copy
b.append(4) # mutate the one shared list
print("a is now:", a) # a sees the change!
print("a is b :", a is b)
b = a never copied anything — it pointed a second name at the one list,
so b.append(4) changed the object both names share. That is why a is
now [1, 2, 3, 4] even though you only ever wrote b.append. And
a is b is True: one object, two labels.
a = [1, 2, 3]
c = a.copy() # a real, independent second list
c.append(99) # change ONLY the copy
print("a :", a) # untouched
print("c :", c)
print("c == a :", c == a) # different values now
print("c is a :", c is a) # and never the same object
print("[1,2,3] == [1,2,3]:", [1, 2, 3] == [1, 2, 3])
print("[1,2,3] is [1,2,3]:", [1, 2, 3] is [1, 2, 3])
a.copy() built a separate object, so appending to c left a as
[1, 2, 3]. Two lists typed out separately are equal by value
(== is True) but are different objects (is is False) — the
two questions == and is ask are genuinely different.
q = 10
r = q
q = 99 # rebinds q to a new object; r is untouched
print("r after rebinding q:", r)
a = 1000
half = 500
computed = half + half # made at runtime, a different object
print("a is computed:", a is computed) # False!
print("a == computed:", a == computed) # True
Rebinding q moved only the label q; r still names the old 10.
And notice the last two lines: a and computed are both 1000 and
equal by value, yet is reports False because they are separate
objects. This is exactly why you must compare numbers with ==, never
is.
Check the concept
One question at a time. Unsure? Revisit the lecture, then answer.
The challenge
Pass the quiz to unlock the challenge — your code will still be waiting here.