0

I have this scenario:

>>> y=[[1]]
>>> y=y*2
>>> y
[[1], [1]]
>>> y[0].append(2)
>>> y
[[1, 2], [1, 2]]

What I'd like to do is add the 2 into the first list within the outer list i.e. this is the desired output:

[[1, 2], [1]]
whytheq
  • 34,466
  • 65
  • 172
  • 267

2 Answers2

1

Doing:

y=[[1]]
y=y*2

creates a list with two references to the same list object:

>>> y=[[1]]
>>> y=y*2
>>> id(y[0])  # The id of the first element...
28864920
>>> id(y[1])  # ...is the same as the id of the second.
28864920
>>>

This means that, when you modify one, the other will be affected as well.


To fix the problem, you can use a list comprehension instead:

>>> y = [[1] for _ in xrange(2)]  # Use range here if you are on Python 3.x
>>> y
[[1], [1]]
>>> id(y[0])  # The id of the first element...
28864920
>>> id(y[1])  # ...is different from the id of the second.
28865520
>>> y[0].append(2)
>>> y
[[1, 2], [1]]
>>>
0

Replace: y=y*2 by y.append([1]) to have different references.

Yves Lange
  • 3,914
  • 3
  • 21
  • 33