Now that we understand how iterators work under the hood, we have all the pieces to put the big picture together. Let’s look back at the following dog_foods
dictionary and the for
loop that performs the iteration:
dog_foods = { "Great Dane Foods": 4, "Min Pip Pup Foods": 10, "Pawsome Pup Foods": 8 } for food_brand in dog_foods: print (food_brand + " has " + str(dog_foods[food_brand]) + " bags")
To summarize, the three main steps are:
The
for
loop will first retrieve an iterator object for thedog_foods
dictionary usingiter()
.Then,
next()
is called on each iteration of thefor
loop to retrieve the next value. This value is set to thefor
loop’s variable,food_brand
.On each
for
loop iteration, the print statement is executed, until finally, thefor
loop executes a call tonext()
that raises theStopIteration
exception. Thefor
loop then exits and is finished iterating.
Let’s review the process in a visual format, before moving on to learn about creating our very own custom iterators!
Instructions
Review the diagram to review the entire process of how for
loops use iterators under the hood.