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

Modify list length within for loop

I know it’s not recommended to change a list while iterating over it, but I’m curious as to why the two different codes below give different results:

numbers = [1,2]
for i in numbers :
    if len(numbers)<3:
        numbers.append(3)
    print(i)

and

numbers = [1,2]
for i in numbers :
    if len(numbers)<3:
        numbers = [1,2,3]
    print(i)

The first code outputs 1,2,3 and the seconde code outputs only 1,2.

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

I would expect both code to behave exactly the same as in both cases I’m modifying the content of the list I’m ranging over.

>Solution :

By writing numbers = [1, 2, 3], you did not change the content of the pre-existing list numbers to [1, 2, 3], you assigned [1, 2, 3] to a new variable.

You need to write numbers[:] = [1, 2, 3] to keep the old list alive and change its content. That will print 1, 2, 3 as you expect.

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