JuniorCodeOccasionalNot answered yet
After b = a on a dict, what do both print after edits?
Predict what each print shows and explain the relationship between a and b.
a = {1: 1}
b = a
a[2] = 2
b[3] = 3
print(a)
print(b)
Determine the output.
Both print {1: 1, 2: 2, 3: 3}. b = a binds a second name to the same dict object — it does not copy it, so edits through either name are visible through both. To get an independent dict use a.copy() or dict(a) (a shallow copy). a is b is True here.
- ✗Thinking
b = acopies the dict instead of aliasing it - ✗Expecting edits through one name not to affect the other
- ✗Confusing name binding with object duplication
- →How would you make
ban independent shallow copy ofa? - →What does
a is breturn here, and what does that test?