4

Possible Duplicate:
Strange behavior of lists in python

I am attempting to initialize a 6 by 6 2D array of None. Here is what I do:

arr = [[None]*6]*6

Then I attempt to insert some values as follows:

arr[2][0] = arr[2][1] = 0

Which instead of changing the values of (2,0) and (2,1) to 0 and keeping the rest of the array full of None, it changes all the columns 0 and 1 to 0.

Full example:

>>> arr = [[None]*6]*6
>>> arr
[[None, None, None, None, None, None], [None, None, None, None, None, None], [None, None, None, None, None, None], [None, None, None, None, None, None], [None, None, None, None, None, None], [None, None, None, None, None, None]]

>>> arr[2][0] = arr[2][1] = 0
>>> arr
[[0, 0, None, None, None, None], [0, 0, None, None, None, None], [0, 0, None, None, None, None], [0, 0, None, None, None, None], [0, 0, None, None, None, None], [0, 0, None, None, None, None]]

Why does this happen and how can I prevent it?

p.s. my use of the phrase 'weird behavior' implies weird to me, not python messing up :)

Community
  • 1
  • 1
Nader Alexan
  • 2,127
  • 22
  • 36

2 Answers2

4

You're making an array with 6 references to the original 6-element array, but you need to have 6 different arrays.

Try

[[None]*6 for i in range(6)]

That will create 6 different arrays.

Eric
  • 3,142
  • 17
  • 14
  • if [[0]*5] is a multiplication of the original element, then why that does not apply to [0]*5 ? – notilas Jun 09 '18 at 03:04
3

When you say [None]*6, a list of six None values is created. When you multiply that by 6, it's six copies of the same list that you get. So modifying one row will also modify all the other rows in the same way.

You can work around this behaviour by doing this (or see this question for alternatives):

arr = [[None]*6 for i in xrange(6)]
Community
  • 1
  • 1
Thomas
  • 174,939
  • 50
  • 355
  • 478