Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

inside nested loops appending list to a new list gives unexpected result

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[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 to list_outer instead of appending a copy of list_inner. This means that when list_inner gets changed, the reference to it that has already been put inside list_outer gets changed as well. So you end up with the same thing repeated in list_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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading