Paul's Python CoursePPC

Iterators hand over one value at a time

Not met yet

An iterator hands over its values one at a time. iter() makes one from a list, a string or a file; next() takes the next value and moves past it. When nothing is left, next() raises StopIteration, or gives back a default if you pass one: next(orders, None). A for loop does the asking for you. An iterator only goes forward, and once it's used up it stays used up.

Try it

main.py
orders = iter(["tea", "cake", "tart"])
print(next(orders))
for order in orders:
    print(order)
print(next(orders, "no more orders"))

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks next() looks at the next value without moving past it.
  • Thinks a for loop over an iterator starts again from the first value, even after next() has taken some.
  • Thinks a used-up iterator or generator starts again from the beginning when it is looped over a second time.
  • Thinks next() works on a list directly, without iter() to make an iterator first.

Where it comes up