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

Time:07-03

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?

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?

CodePudding user response:

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.

  • Related