Iterating and Updating the list in python

Viewed 3195

I am not able to understand why the following code goes in indefinite loop(when i am not using the copy list)

list = ["Mohit","kumar","sffsfshfsd"]
for w in list:
    if(len(w)) > 5:
        list.insert(0,w)
    print("inside loop")

print(list)  

The Above code prints inside loop indefinitely.

Now if in place of the list, i use a copy list like below works fine.

list = ["mohit","kumar","sffffgssddf"]

for w in list[:]:
    if len(w) > 5:
        list.insert(0,w)
    print("inside loop")

print(list)  

Now i have read in the python documentation that this is the behavior i will get but i want to understand the reason behind it. Thanks in advance.

6 Answers
Related