Say I have a 2D array of 4 rows and 5 cols. I want to assign only the first row elements with their respective indices to get the below 2D array.
0 1 2 3 4
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
I first tried this:
array1 = [[0]*cols]*rows
print(array1)
for i in range(cols):
array1[0][i] = i
print(array1)
Result:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Which is not what I intended to do. Every row is being updated instead of just the first one.
But the following code gives the result I'm looking for.
array2 = [[0 for x in range(cols)] for y in range(rows)]
print(array2)
for i in range(cols):
array2[0][i] = i
print(array2)
Result :
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[0, 1, 2, 3, 4], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
The only difference between both the snippets is the way array1 and array2 have been initialized. I'm curious to know why both of them work differently. Would appreciate any help.
-Thank You