Home > Mobile >  Python 2D Array/List Assignment Gives Unwanted Result
Python 2D Array/List Assignment Gives Unwanted Result

Time:10-10

Say, I have a 2-dimensional list/array that contains 50 subarrays that look like [0, 0]. I want to change only some parts of the array, say the first elements of each subarray from index 15 to 29. I used a for loop to do this.

array = [[0,0]] * 50
for i in range(15, 30):
    array[i][0] = 1

But when I print(array), it seems like the program changes all the first elements of each subarray. Output:

[[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]

I do not know what I am doing wrong, as the logic seems sound. Can anyone identify my mistake?

CodePudding user response:

array = [[0,0]] * 50 By this, your array will have [0,0] 50 times referencing to same [0,0]. So modifying one will modify all of them.
Instead try this: array = [[0, 0] for _ in range(50)].

  • Related