[Solved] How for loop in Python work?


When you iterate through a list in Python, any modifications to the list you are iterating through will have an effect on the for loop. For example, take this code:

my_list = list()
my_list.append("hello")
for element in my_list:
    my_list.append("hello")

This code will run forever, because my_list keeps growing in size.

With your code, you have to think about what is happening inside the for loop.

There are two instances of ‘abc’ in your list, so after the first iteration, where the first element in the list is checked, they are both removed from Sentence. This leaves a list that looks like this

['bcd', 'cde', 'dea', 'eab']

Now, Python checks the second element in the list. This is where the issue is caused. Python skips over the ‘bcd’ element and moves straight on to ‘cde’, removing ‘cde’ from Sentence, leaving a list that looks like this:

['bcd', 'dea', 'eab']

Now, Python checks the 3rd element in the list, which is ‘eab’ and then removes it from the list, and then Python knows that there are no more elements in Sentence to iterate through because it has reached the end and the for loop breaks, leaving Sentence like this

['bcd', 'dea']

I’m not entirely sure what exactly you want your code to do in the end so I can’t really propose a solution but I hope this makes sense.

solved How for loop in Python work?