NepNep
NepNep

Reputation: 274

Initialize 2D list

The follow codes didn't behave like I expected. Is this an incorrect way of initializing a 2D list filled with 0?

matrix = [[0] * 4] * 4
for row in matrix:
    print(row)
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]


matrix[0][0] = 1
for row in matrix:
    print(row)
[1, 0, 0, 0]
[1, 0, 0, 0]
[1, 0, 0, 0]
[1, 0, 0, 0]

Upvotes: 0

Views: 583

Answers (4)

Stuart
Stuart

Reputation: 9858

In the general case you can make something like numpy.full (but for lists instead of arrays):

def full(shape, fill_value=0):
    if len(shape) > 1:
        return [full(shape[1:], fill_value) for _ in range(shape[0])]
    else:
        return [fill_value] * shape[0]

matrix = full((4, 4), 0)

Upvotes: 0

Derek O
Derek O

Reputation: 19545

That is because the matrix is composed of a copy of the list [0,0,0,0].

This should work:

matrix = [[0 for i in range(4)] for j in range(4)]
matrix[0][0] = 1

Upvotes: 1

ch4rl1e97
ch4rl1e97

Reputation: 686

I actually ran into this problem a while ago! No, this isn't the correct way, at least for what you're expecting to happen.

The problem is that when you initialise this list, you create a list of references back to the first item, so when you modify it, you modify all of them, because in reality they all point to the same object in memory.

Instead of that you can do something like this:

x = 4
y = 4
matrix = [[0]*x for _ in range(y)]

With a result of:

[[0, 0, 0, 0], 
[0, 0, 0, 0], 
[0, 0, 0, 0], 
[0, 0, 0, 0]]

Then matrix[0][0] = 1 only sets the first element of the first list to 1.

You can extend this into 3D and beyond by simply adding a new layer of for __ in range(z) on the end and and wrapping it in more square brackets.

Upvotes: 1

dildeolupbiten
dildeolupbiten

Reputation: 1342

Use matrix = [[0 for i in range(4)] for j in range(4)] instead of matrix = [[0] * 4] * 4.

matrix = [[0 for i in range(4)] for j in range(4)]
matrix[0][0] = 1
for row in matrix:
    print(row)

Output:

[1, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]

Upvotes: 4

Related Questions