Python For Loop Skips Item
Solution 1:
First things first, it's actually breakfast rather than breakfeast. What you're breaking (ending) is the fast (going without food) rather than the feast (having lots of food).
But that's just me being pedantic :-)
Now, on to the actual question. You should not modify the list while enumerating it (technically, you are allowed to do this but you will get strange results like you've seen).
Doing so messes up the internal structures used for the enumeration. This is a simplified explanation but it should illustrate the concept:
Think of the enumeration as just stepping through each element in animals
using the index.
When you get to index 2 (waffle) and you find it's in breakfast_foods
, you remove the item at that index and shuffle the other ones along so that you now have:
['cat', 'dog', 'giraffe', 'turtle']
Then the enumeration moves on to index 3 (which is now turtle) and you print that out, skipping giraffe in the process.
In any case, perhaps a more Pythonic way of doing this would be:
animals = [x for x in animals if x not in breakfast_foods]
Whether a particular implementation of Python uses simple arrays or other data structures is not really important here. The explanation is simply to illustrate that changing a data structure while iterating over it can often cause weirdness.
Post a Comment for "Python For Loop Skips Item"