python - Why does += behave unexpectedly on lists? - Stack Overflow

PHOTO EMBED

Sat Feb 19 2022 10:58:31 GMT+0000 (Coordinated Universal Time)

Saved by [deleted user]

>>> a1 = a2 = [1, 2]
>>> b1 = b2 = [1, 2]
>>> a1 += [3]          # Uses __iadd__, modifies a1 in-place
>>> b1 = b1 + [3]      # Uses __add__, creates new list, assigns it to b1
>>> a2
[1, 2, 3]              # a1 and a2 are still the same list
>>> b2
[1, 2]                 # whereas only b1 was changed
content_copyCOPY

https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists