Evaine LeBlanc
Evaine LeBlanc

Reputation: 81

Appending to a specific element of a 2D array

I have this list arr containing n empty list and another list indices with integers ranging from 0 to n-1

    n = 4
    e = []
    arr = [e]*(n)
    indices = [0,2,3,0,2,1,3]

What I want to do is to get each element i in indices and append some variable to the ith element of arr. Code is shown below

    var = 1
    for i in indices:
        arr[i].append(var)

I was expeting arr will have two elements on its first list, one on its second, etc. However when I print arr, I get the following

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

Upvotes: 0

Views: 81

Answers (1)

Mahrad Hanaforoosh
Mahrad Hanaforoosh

Reputation: 546

try changing the first block as follows:

n = 4
arr = [[] for i in range(n)]
indices = [0,2,3,0,2,1,3]

now everything is ok.

More info

when you defined arr as arr = [e]*(n) every list inside arr was referring to the same place in the memory (i.e. e). so, changing one element inside arr would change all of the elements. but when you define arr as arr = [[] for i in range(n)] then the element would be independent.

Upvotes: 1

Related Questions