Number changes in all row of array
Question:
I created a 4×5 2D array using python, and when I wanted to change a number inside it, it automatically changes the number in every row
rows,cols = (4,5)
arr = [[0]*cols]*rows
print (arr)
And this is how the output shows
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
After I created the array, I decide to change a number in the first row
arr[0][2] = 3
print(arr)
But it appears like this
[[0, 0, 3, 0, 0], [0, 0, 3, 0, 0], [0, 0, 3, 0, 0], [0, 0, 3, 0, 0]]
I checked with it and I still can’t find any problem in it. May someone help me with it?
Answers:
‘Multiplying’ the list copies the value references repeatedly – which is fine for primitives but not so much for lists, like you’ve seen. If you want different instances of the list, you could use list comprehension:
rows, cols = (4, 5)
arr = [[0] * cols for _ in range(rows)]
arr[0][2] = 3
print(arr) # [[0, 0, 3, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
I created a 4×5 2D array using python, and when I wanted to change a number inside it, it automatically changes the number in every row
rows,cols = (4,5)
arr = [[0]*cols]*rows
print (arr)
And this is how the output shows
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
After I created the array, I decide to change a number in the first row
arr[0][2] = 3
print(arr)
But it appears like this
[[0, 0, 3, 0, 0], [0, 0, 3, 0, 0], [0, 0, 3, 0, 0], [0, 0, 3, 0, 0]]
I checked with it and I still can’t find any problem in it. May someone help me with it?
‘Multiplying’ the list copies the value references repeatedly – which is fine for primitives but not so much for lists, like you’ve seen. If you want different instances of the list, you could use list comprehension:
rows, cols = (4, 5)
arr = [[0] * cols for _ in range(rows)]
arr[0][2] = 3
print(arr) # [[0, 0, 3, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]