Search code examples
pythonarrayslistnested2d

2D lists Not indexing correctly


I have the following simple 2D lists program:

rowMatrix = [0]*4
matrix = [rowMatrix]*4

for a in range(4):
    for b in range(4):
        matrix[a][b] = random.randrange(0,2)
print(matrix)`

It seems like it would put random numbers (0, 1) in all 16 cells of the 4x4 array. But all 4 rows are identical every time. What's wrong?


Solution

  • The following line creates four list elements which are actually the same list:

    matrix = [rowMatrix]*4
    

    This means modifying matrix[0][0] also modifies the other lists.