filling 2D Matrix in row major order

Viewed 114

I tried to make a 2D array using list in python in this method:

N = 3
A = [[0]*N]*N 
for i in range(N):
    for j in range(N):
        A[i][j] = (i*N + j+1)
print (A)

The output was:

[[7, 8, 9], [7, 8, 9], [7, 8, 9]]

i wanted output like this:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Can someone please tell me what is wrong in this code?

2 Answers

The problem is you used A = [[0]*N]*N to initialize A. This is a copy by reference method! This means that elements within A point to the same cell in memory and hence, when you assign a value to A, you assign that same value to multiple cells within A! More precisely, what happens within your code is that the final loop of i overrides all the previous written results with [7 8 9] and so you get [[7,8,9], [7,8,9], [7,8,9]] instead of [[1, 2, 3], [4, 5, 6], [7, 8, 9].

Here is a fix, which initializes A without references:

N = 3
A = [[[0] for k in range(N)] for m in range(N)]
for i in range(N):
    for j in range(N):
        A[i][j] = (i*N + j+1)
print (A)

When initializing A using list comprehension as above, each cell within A points to a different place in memory and so the result is as you wished:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]

The problem is you are creating list [0] *N and then placing it 3 times into another list

Running the code below will show how at each iteration if the loop all three lists are modified at the same time


N = 3
A = [[0]*N]*N 
for i in range(N):
    for j in range(N):
        print(i*N +j +1)
        print(A)
        A[i][j] = (i*N +j +1)
print (A)

You could initialize it with a list comprehension instead

N = 3
A = [[[0] for i in range(N)] for j in range(N)]
for i in range(N):
    for j in range(N):
        print(i*N +j +1)
        print(A)
        A[i][j] = (i*N +j +1)
print (A)
Related