Reputation: 1
I am learning Python and, during an exercise, I got into this situation:
words = ['one', 'two', 'three']
for w in words
if len(w) == 5:
words.insert(0,w)
Now, what happened here was that while the loop was iterating over the last word and found a match, it inserted the new word at the beginning of the list and continued the loop as the length of the list has increased by 1. This resulted in an infinite loop.
Now, I changed the code like this:
words = ['one', 'two', 'three']
for w in words[:]
if len(w) == 5:
words.insert(0,w)
The result was exactly as I anticipated. There was only one word addition at the beginning and exited the loop.
Can someone explain what exactly was happening in the first code?
Upvotes: 0
Views: 1115
Reputation: 56467
You iterated over the list which you modified in the loop. Bad idea in most cases.
Perhaps what you are missing is that words[:]
creates a copy of words
. You iterate over the copy so when you add to the original list everything is fine.
Upvotes: 2