Part 2 · Section 06

Generators

Writing an iterator class by hand works, but it’s a lot of ceremony: an __init__ to store state, an __iter__ that returns self, and a __next__ that remembers where it left off and raises StopIteration at the right moment. A generator gets you the same thing with an ordinary-looking function. The trick is the yield keyword, which hands a value back to the caller and pauses the function, keeping all its local variables, until the next value is requested.

In this section you’ll learn:

Lectures

  1. 01Yielding and Generators✓
  2. 02Example - Fibonacci Sequence✓
  3. 03Making an Iterable from a Generator✓
  4. 04Example - Card Deck✓
  5. 05Generator Expressions✓
  6. 06Yield From✓

Practice: quiz & exercises

12 quiz questions · 4 coding exercises

Go to practice →