2

I want to create a 2D array, like so:

grid[y][x] 

So that there are y amount of rows and x amount of columns.

Below is the way I did it, but I when I tried to assign the (0,0) of the array to contain the value '2', the code assigned the first value of each subarray to '2'.

Why is this happening? How should I pythonically instantiate a 2D array?

n = 4 
x=0 
y=0 
grid = [[None]*n]*n 

print grid 

grid[y][x]='Here' 

print grid
purpleladydragons
  • 1,305
  • 3
  • 12
  • 28
  • Possible duplicate of http://stackoverflow.com/questions/6688223/python-list-multiplication-3-makes-3-lists-which-mirror-each-other-when – srgerg Jan 30 '12 at 23:30
  • See http://stackoverflow.com/questions/1959744/python-list-problem or http://stackoverflow.com/questions/3859301/create-2d-array-in-python or http://stackoverflow.com/questions/7745562/appending-to-2d-lists-in-python -- this is a common beginner question. – DSM Jan 30 '12 at 23:31
  • Consider `grid = {}; grid[0,0] = 'Here'`. – Russell Borogove Jan 30 '12 at 23:38

2 Answers2

3

when you use * you create multiple references, it does not copy the data so when you modify the first line to

[here,none,none,none] 

you actually change all lines.

solution

[[None for i in range(n)] for j in range(n)]

Edit (from other post) Since only the lists are mutable (can change in place) you can also do

[[None]*n for j in range(n)]. 

Each of the rows are then still unique. If the None object could be changed in place this would not work.

Johan Lundberg
  • 26,184
  • 12
  • 71
  • 97
0
grid = [[None]*n for i in range(n)]
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622