2

I found that there is a difference between extending a list with x += [0] and x = x + [0].

x = [1]
y = x
x += [0]
print(x, y)

The above prints [1,0] [1,0]. Compared to below:

x = [1]
y = x
x = x + [0]
print(x, y)

which prints [1, 0] [1]. Why does this happen?

Tim K
  • 39
  • 6
  • 4
    Does this answer your question? [Why does += behave unexpectedly on lists?](https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists) – GoodDeeds Feb 04 '20 at 15:32
  • 3
    `list.__iadd__` updates `x` in-place; `list.__add__` does not. – chepner Feb 04 '20 at 15:32

0 Answers0