Home > Software design >  Getting an Infinite Loop in for statement in python. What is wrong in this code?
Getting an Infinite Loop in for statement in python. What is wrong in this code?

Time:04-07

I am new to python and was trying some code stuff and erroneously found this. I am not able to understand the behaviour of code? what is causing infinite loop ?

any_list=[""]
 
for x in any_list:

   any_list.append("something")

CodePudding user response:

It's because you are looping and adding an item to the any_list at the same time. So it goes on forever.

CodePudding user response:

You are adding a new item to the list each iteration, thus causing the length of any_list to increase, which extends the loop.

  • Related