MiddleCodeOccasionalNot answered yet
What do += and + print for these aliased lists?
Predict both print(b) lines.
a = [1, 2, 3]
b = a
a += [4] # (1)
print(b)
a = [1, 2, 3]
b = a
a = a + [4] # (2)
print(b)
Determine the output and explain.
[1, 2, 3, 4] then [1, 2, 3]. += on a list calls __iadd__, mutating the object in place, so b (same object) sees it. a = a + [4] builds a new list and rebinds a, leaving b pointing at the original — mutation versus rebinding.
- ✗Believing
+=and+behave identically on lists - ✗Thinking
b = acopies the list - ✗Not distinguishing in-place mutation from rebinding
- →What does
__iadd__return, and why does that matter for the rebinding? - →How would the result differ if
awere a tuple instead of a list?