Create multi-dimensional arrays in pure Python: The Correct Way
The problem Yesterday I wasted about half an hour chasing a bug because I was mindlessly generating a 5x5 matrix with the list repeat syntax, aka list * integer in pure Python: n = 5 array = [[0] * n] * n When I tried to flip some specific bits in this matrix, I observed that entire columns got flipped, instead of just one element: array[0][0] = 1 print(array) # Output: [[1, 0, 0, 0, 0], # [1, 0, 0, 0, 0], # [1, 0, 0, 0, 0], # [1, 0, 0, 0, 0], # [1, 0, 0, 0, 0]] In retrospect, the behaviour makes sense, but in the middle of a much larger program, it was a bit hard to find....