-1

Possible Duplicate:
Python list append behavior

Why does this code:

x = [[]]*3
x[0].append('a')
x[1].append('b')
x[2].append('c')
x[0]=['d']

print x

print [['d'], ['a', 'b', 'c'], ['a', 'b', 'c']]?

Community
  • 1
  • 1
sashab
  • 1,534
  • 2
  • 19
  • 36
  • 1
    This question is literally asked about once a day... The problem seems to be that you can't search for the solution unless you already know what's going on. – Niklas B. Mar 31 '12 at 13:09
  • to prohibit such behaviour, it's better to create list of lists using this following syntax.>>> x=[[] for _ in range(3)] – Ashwini Chaudhary Mar 31 '12 at 15:44

1 Answers1

5

This is best explained step by step:

>>> x = [[]]*3
>>> x
[[], [], []]
>>> x[0].append('a')
>>> x
[['a'], ['a'], ['a']]
>>> x[1].append('b')
>>> x
[['a', 'b'], ['a', 'b'], ['a', 'b']]
>>> x[2].append('c')
>>> x
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
>>> x[0]=['d']
>>> x
[['d'], ['a', 'b', 'c'], ['a', 'b', 'c']]

The first statement creates a list with three references to the same element in it. So when you modify the first element, you're also modifying the second and third element. Hence, the append statements add a number to each of the elements of the list.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
  • I know it's tempting but there are already 50 good answers to this question. Just link a duplciate in a comment and / or flag it as a duplicate until you have enough rep to vote to close. – agf Mar 31 '12 at 13:21
  • Operator * acting on the lists makes shallow copies — that is. – sashab Mar 31 '12 at 18:05