Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error modifying one element in a Python list [duplicate]

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.

like image 460
Aung Khant Ko Avatar asked Jan 31 '26 05:01

Aung Khant Ko


1 Answers

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.

like image 88
FHTMitchell Avatar answered Feb 02 '26 19:02

FHTMitchell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!