purpleladydragons
purpleladydragons

Reputation: 1305

2D Array Unintended Assignment Bug

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

Upvotes: 2

Views: 429

Answers (2)

Johan Lundberg
Johan Lundberg

Reputation: 27028

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.

Upvotes: 3

Mark Ransom
Mark Ransom

Reputation: 308206

grid = [[None]*n for i in range(n)]

Upvotes: 0

Related Questions