Question

I have been using python for a lot and today I get surprised by a simple nested list.

How can I change the value of an element of my list?

>>> l=[[0,0]]*10
>>> l
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
>>> l[0]
[0, 0]
>>> l[0][0]
0
>>> l[0][0]=1 #here comes the question
>>> l
[[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]
>>> 

I would expect as final result

l=[[1,0],[0,0],[0,0]...]

Why it does not append? (I would like a theoretical explanation ) How can I get the desired result?

Thanks.

EDIT: In starting the list in another way I get the desired result

>> l=[[0,0],[0,0]]
>>> l
[[0, 0], [0, 0]]
>>> l[0][0]=1
>>> l
[[1, 0], [0, 0]]
>>> 

but I am still wondering why the first version does not work and how can I initialize a list of a lot of elements?

Was it helpful?

Solution

You have a list of the same [0, 0] element 10 times here:

l=[[0,0]]*10

Any time you modify one, it modifies them all, because they're the same list.

One safe way to make them unique would be:

l = [[0, 0] for _ in range(10)]

One easy way to check would be to print the id of each, which is the memory address where it's stored:

>>> for element in l:
...     print id(element)
...
34669128
34669128
34669128
34669128
34669128
34669128
34669128
34669128
34669128
34669128
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top