I have tried to write my error issue in reproducible manner for platform to be seen and guided. I cannot see my logic gap why this error happens.
I have a inner loop which brings new elements while scraping and appends it to list named list_inner
. Then in outer loop list named list_outer
appends that new list. But final result gives amount of members right, but elements of list list_outer are same, the last list element of list list_inner
. How can this happen? If it will be one elemented list I will understand.
import random
list_inner=[]
list_outer=[]
for i in range(5):
for r in range(random.randint(1,10)):
list_inner.append(r)
print(r)
list_outer.append(list_inner)
print(list_outer)
print(list_outer)
I am sharing for two results, as giving idea what is in real and what I was expecting. I got this result:
0
1
2
3
[[0, 1, 2, 3]]
0
1
2
3
4
[[0, 1, 2, 3, 0, 1, 2, 3, 4], [0, 1, 2, 3, 0, 1, 2, 3, 4]]
But I was expecting this result:
[[0,1,2,3],[0,1,2,3,4]]
>Solution :
There are really two problems here:
- You are not clearing
list_inner
at the end of each outer loop, so it retains all the elements from all the iterations so far - You are appending
list_inner
directly tolist_outer
instead of appending a copy oflist_inner
. This means that whenlist_inner
gets changed, the reference to it that has already been put insidelist_outer
gets changed as well. So you end up with the same thing repeated inlist_outer
.
All you need to do is change your code to copy list_inner
before appending it, and also clear list_inner
at the end of each outer loop:
import random
list_inner = []
list_outer = []
for i in range(5):
for r in range(random.randint(1,10)):
list_inner.append(r)
list_outer.append(list_inner.copy())
list_inner.clear()
print(list_outer)
Example output:
[[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2], [0, 1, 2, 3, 4, 5, 6], [0, 1], [0, 1, 2, 3]]