1

Possible Duplicate:
Python list confusion

I am newbie to python. Please let me know why do stairlist[1][0] = 2 statement changes all the values when initialized with stairlist = [[0,0]] * 8.

>>> stairlist = [[0,0]] * 8
>>> stairlist
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
>>> stairlist[1][0] = 2
>>> stairlist
[[2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0]]

But when I initialize stairlist variable according to the following then it works fine.

>>> stairlist = [[1,2],[1,2]]
>>> stairlist
[[1, 2], [1, 2]]
>>> stairlist[1][1] = 3
>>> stairlist
[[1, 2], [1, 3]]
Community
  • 1
  • 1
Sushant Jain
  • 328
  • 2
  • 6
  • 12
  • Looks like the `[[0,0]] * 8` syntax is using aliases instead of independent copies. Not sure whether this is in the spec, or is an implementation issue. – jpm Mar 30 '12 at 20:33
  • @jpm: Yes, it's in the spec. It's called *sequence repetition*. See http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange note (2), and notice that the copies are defined to be shallow copies. – Adam Rosenfield Mar 30 '12 at 20:39
  • @FelixKling Thanks, I found the solution. Actually it was difficult for me to find the similar question due to question title problem. – Sushant Jain Mar 30 '12 at 20:41

1 Answers1

2

array * number will create a new array by making a shallow copy of each object in the original array, number times.

since [0,0] is itself an array, and thus a proper object, the new array just contains a bunch of references to the same [0,0] array. when you change one, you change all of them.

for comparison:

simplelist = [0] * 8
[0, 0, 0, 0, 0, 0, 0, 0]
simplelist[1] = 2
[0, 2, 0, 0, 0, 0, 0, 0]
YenTheFirst
  • 2,172
  • 13
  • 11
  • What do you mean "and thus a proper object"? An `int` is a proper object. Also, the type is called a `list`. Since this isn't true for all arrays in general, you need to be specific. What exactly is your example trying to show? You're not doing the same thing he was. If he were to do `stairlist[1] = 2` he'd get the exact same behavior. – agf Mar 30 '12 at 20:44