Search code examples
pythonlistin-place

Error modifying one element in a Python list


I am trying to change an element in a Python list. Following the tutorial on https://www.programiz.com/python-programming/matrix, I came up with the code below.

 matrix = [[0]*6]*3
 print(matrix)
 matrix[0][0] = 2
 print(matrix)

Upon running the code, I received the following output:

[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
[[2, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0]]

Notice the last line of output, how the first element of every sub-list is set to 2. How do I make it so that only the first element of the first list is changed.


Solution

  • This is a classic python gotcha to do with the fact that all python objects are references. In your case this means that matrix[0] is matrix[1] is matrix[2] since is is True if two objects are the same thing in memory.

    Do this instead

    matrix = [[0]*6 for _ in range(3)]
    

    Now matrix[0] is matrix[1] is matrix[2] returns False.

    Alternatively, use numpy which was made for manipulating numerical arrays without these issues.