First page Back Continue Last page Overview Graphics
Iterators in for Loops
>>> cities = ["Paris","Berlin","London"]
>>> for city in cities:
... print("city: " + city)
...
city: Paris
city: Berlin
city: London
Whats happening?
- The built-in function iter with iter(cities), which calls __iter__ of the list class. The return value – a „list_iterator” - is stored in a variable, e.g. iter_x.
- After each loop the next function ist called with iter_x as an argument and the return value of this call is assigned to the variable iter_x.
- The loop will be repeated until next(iter_x) raises the exception StopIteration.