Reputation: 81
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
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.
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