Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Iterators vs Generators

  • a generator is an iterator
  • an iterator is an iterable
from collections.abc import Iterator, Iterable
from types import GeneratorType

print( issubclass(GeneratorType, Iterator) )  # True
print( issubclass(Iterator, Iterable) )       # True

  • Genarators are a simpler way to create an iterable object than iterators, but iterators allow for more complex iterables.
  • To create an iterator we need a class with two methods: __iter__ and __next__, and a raise StopIteration.
  • To create a generator we only need a single function with `yield .