0

New to python and having trouble with populating a list.

mat = [[0]*3]*4

for i in range(4):
  for j in range(3):
    mat[i][j] = (i,j)

print(mat)

The piece of code above prints out:

[[(3, 0), (3, 1), (3, 2)],
 [(3, 0), (3, 1), (3, 2)],
 [(3, 0), (3, 1), (3, 2)],
 [(3, 0), (3, 1), (3, 2)]]

When I thought it should print out something like:

[[(0, 0), (0, 1), (0, 2)],
 [(1, 0), (1, 1), (1, 2)],
 [(2, 0), (2, 1), (2, 2)],
 [(3, 0), (3, 1), (3, 2)]]

I realize this might be a simple question, but what am I doing wrong? Everywhere online tells me to populate a list this way as well.

Thanks in advance!

idude
  • 4,654
  • 8
  • 35
  • 49

2 Answers2

3

When you create the original array the way you did parts of the matrix are sharing the same reference: mat[0] is mat[1] => True! This make the same array and repeats 4 references to it: [[0]*3]*4, so when you change one, you change them all.

One way to avoid this by creating the subarrays as you go:

mat = []

for i in range(4):
    mat.append([])
    for j in range(3):
        mat[i].append((i,j))

print(mat)
# [[(0, 0), (0, 1), (0, 2)], [(1, 0), (1, 1), (1, 2)], [(2, 0), (2, 1), (2, 2)], [(3, 0), (3, 1), (3, 2)]]
Mark
  • 90,562
  • 7
  • 108
  • 148
1
mat = [[0]*3]*4.
mat[0][1] = 1

print(mat)

As you can see all the rows of the array have been changed to match the initial. This is because in python the way you created the list duplicated the same original row, meaning all the other rows will point to the same memory address so they will all be affected.

To fix this try this instead:

mat=[[0]*3 for i in range(4)]

This makes everything in the list independent.

Chris A
  • 19
  • 3