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

Why does list.append(temporary variable) in for loop return infinite loop?

Newbie here. Can you please explain why the following lines of code return an infinite loop?

First:

list = [1,2,3]
for i in list:
   list.append(1)

Why does it return an infinite loop and does not add 3 "1" elements to the list?

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

Second:

list = [1,2,3]
for i in list:
   list.append(i)

Same here, returns an infinite loop of the list [1,2,3].

Third:
Why does the following snippet of code not return anything(even an infinite loop) to the terminal?

list = [1,2,3]
for i in list:
   list.append(1)

print(list)

Can you please explain the logic or the order behind the loop?

>Solution :

The infinite loop is created because you are appending a value to your list WHILE (not after) you’re iterating over it.

You’re saying for every element in your list (3 total), append one element of value 1 (thus adding 3 more), but you’re still in the for i in list part, so you would then have to append one element of value 1 to every element in your list (now 6), and so on.

Same thing for your second example, except the value is i instead of 1.

Third snippet is never reaching the print(list) as you’re in an infinite loop above, until that loop is over (which would be never) the following code would not run.

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