1

Personally for me, this code gives strange output, I don't understand why.

Input:

matrix = [[0] * 5] * 5

for i in range(5):
    matrix[i][0] = i

matrix

Output:

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

Expected output:

[[0, 0, 0, 0, 0],
 [1, 0, 0, 0, 0],
 [2, 0, 0, 0, 0],
 [3, 0, 0, 0, 0],
 [4, 0, 0, 0, 0]]
  • Basically, you're multiplying a list. Lists in python are by reference, so when you update 1 you're updating all of them. A way around this is list comprehensions: `matrix = [[0] * 5 for a in range(5)]`. The included link will be quite useful though. – Neil Nov 14 '17 at 21:25

0 Answers0