3

I had learnt about the Mutability of Lists and was trying to see how it works. However, I observed something new:

x = [1, 2, 3]
y = x
print x # [1, 2, 3]
y += [3, 2, 1]
print x # [1, 2, 3, 3, 2, 1]

works all right

However, if I replace y += [3,2,1] by y = y + [3,2,1], I get the following result:

x = [1, 2, 3]
y = x
print x # [1, 2, 3]
y = y+ [3, 2, 1]
print x # [1, 2, 3]

which isn't what I had expected. Can someone please tell me how y+= is giving a different result?

Dhruv Mullick
  • 551
  • 9
  • 25

2 Answers2

1

when you do:

y = y+ [3, 2, 1] 

you are creating a new list y with new reference, and that does not affect the old one.

Ammar
  • 1,305
  • 2
  • 11
  • 16
1

It's been answered somewhere before, but long story short:

x = x + y means basically assign x+y to x (so x references a new object)

x += y means add y to x (so x still references the same object)

Dunno
  • 3,632
  • 3
  • 28
  • 43