2

I am trying to add/replace an i element on the i-th list of a list, however, only the last iteration is saved. It would be great to understand why this happens and what a workaround this would be. I'm interested in an output that looks like this: [[[0], [], [], []], [[1], [], [], []], [[2], [], [], []], [[3], [], [], []]], but instead I get this: [[[3], [], [], []], [[3], [], [], []], [[3], [], [], []], [[3], [], [], []]]

matrix = [ [ [] * 4] * 4] * 4
print('pre_matrix=',matrix)
for m in range(len(a) + 1):
    matrix[m][0] = [m]
    print('m={}, matrix[m]={}'.format(m, matrix[m]))
print('post_matrix=', matrix)

# This is what the response looks like:
# pre_matrix= [[[], [], [], []], 
# [[], [], [], []], 
# [[], [], [], []], 
# [[], [], [], []]]
#
# m=0, matrix[m]=[[0], [], [], []]
# m=1, matrix[m]=[[1], [], [], []]
# m=2, matrix[m]=[[2], [], [], []]
# m=3, matrix[m]=[[3], [], [], []]
#
# post_matrix= [[[3], [], [], []], 
# [[3], [], [], []], 
# [[3], [], [], []], 
# [[3], [], [], []]]
Yuna Luzi
  • 318
  • 2
  • 9

1 Answers1

3

When you do something like:

matrix = [ [ [] * 4] * 4] * 4

You are actually not creating new lists with each multiplication. Instead, you are creating many references to the same underlying list. This can be seen when we simplify the example:

matrix = [[0, 0, 0]] * 3 # <- Wrong!
matrix[0][0] = 1
print(matrix)
# [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

To fix this, use list comprehensions to properly create a new list each time:

matrix = [[[] for _ in range(4)] for _ in range(4)]

In your code (replacing len(a) + 1 with 4):

matrix = [[[] for _ in range(4)] for _ in range(4)]
print('pre_matrix=',matrix)
for m in range(4):
    matrix[m][0] = [m]
    print('m={}, matrix[m]={}'.format(m, matrix[m]))
print('post_matrix=', matrix)

Output:

pre_matrix= [[[], [], [], []], [[], [], [], []], [[], [], [], []], [[], [], [], []]]
m=0, matrix[m]=[[0], [], [], []]
m=1, matrix[m]=[[1], [], [], []]
m=2, matrix[m]=[[2], [], [], []]
m=3, matrix[m]=[[3], [], [], []]
post_matrix= [[[0], [], [], []], [[1], [], [], []], [[2], [], [], []], [[3], [], [], []]]
iz_
  • 15,923
  • 3
  • 25
  • 40