-1

I have this code:

x = 'x'
y = []
y.append(x)
z = y
z.append('a')
x = 'X'

print "x:", x
print "y:", y
print "z:", z

output:

x: X
y: ['x', 'a']
z: ['x', 'a']

I know that this is the correct output, but I am having a hard time understanding why it produces

y: ['x', 'a']

instead of

y: ['x']
e h
  • 8,435
  • 7
  • 40
  • 58
  • Answers to this kind of questions should be empeded to allow the closing and tagging as "duplicate", instead of being answered again and again after having been answered hundreds of times. Will this kind of question be answered until the end of life of stackoverflow in 1000 years ? I'm also shocked that there are so much people upvoting answers, particularly to members at the top of reputation scores. – eyquem Dec 13 '13 at 19:36

2 Answers2

6

By assigning y to z, you did not create a copy of the list. You merely created another reference to the same list object.

If you wanted y to be a copy of the list, you need to create such a copy explicitly:

z = list(y)

or

z = y[:]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Your current code creates z to be a reference to y itself. Meaning, both z and y point to the same list object in memory.

To fix the problem, make z a copy of y instead of a reference to it:

z = y[:]

Below is a demonstration:

>>> x = 'x'
>>> y = []
>>> y.append(x)
>>> z = y[:] # Make z a copy of y
>>> z.append('a')
>>> x = 'X'
>>> print "x:", x
x: X
>>> print "y:", y
y: ['x']
>>> print "z:", z
z: ['x', 'a']
>>>