An error occurred while modifying an element in the Python list… here is a solution to the problem.
An error occurred while modifying an element in the Python list
I’m trying to change an element in a Python list. Follow 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)
After running the code, I get 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 how the last element of each sublist is set to 2
on the last line of the output. How can I change only the first element of the first list.