-1

I'm learning Python and just came across the following behaviour.

I define a list x and assign (what I think is) the values of x to the variable y.

>>> x = [1,2,3]
>>> y = x
>>> y.extend([4,5,6])
>>> print y
[1, 2, 3, 4, 5, 6]
>>> print x
[1, 2, 3, 4, 5, 6]

But after extend'ing the list y, both x and y has the extra three elements. The same goes for append.

>>> x = [1,2]
>>> y = x
>>> y.append(3)
>>> print y
[1, 2, 3]
>>> print x
[1, 2, 3]

I understood the assign operator = as assigning from right to left, what am I not getting?

How can I assign a list from a named list but still be able to alter the new list without affecting the old one? Or is this not the right way to handle lists in Python?

Duffau
  • 471
  • 5
  • 15

1 Answers1

1

y = x assigns y to be the same list as x. Instead, you should copy the list. One way to do this is:

y = list(x)
Pandu
  • 1,606
  • 1
  • 12
  • 23
  • Ok thanks. Does this only apply to lists? Because i tried adding something an int and it did not do the same thing. – Duffau Aug 26 '15 at 22:11
  • In many programming languages, (including Python) this applies to objects, (like lists) but not primitives. (like ints) That is, you have to copy objects, but not primitives. – Pandu Aug 26 '15 at 22:12
  • Ok good to know! Thanks. – Duffau Aug 26 '15 at 22:19