Python ยท Chapter 30 of 45

Iterators & Generators

An ITERATOR yields values one at a time via the `__next__` protocol. A GENERATOR is a simple way to write iterators using `yield`.

Generators are memory-efficient โ€” they compute values on demand rather than building a whole list.

yield

Any function containing `yield` becomes a generator. Calling it returns a generator object, not the value.

When to use

For large or infinite sequences, streaming data, or lazily transforming an iterable.

Example 1 (python)
def count_up(n):
    i = 1
    while i <= n:
        yield i
        i += 1

for x in count_up(3):
    print(x)
Output
1
2
3

yield produces one value per iteration.

Example 2 (python)
squares = (x*x for x in range(4))
print(list(squares))
Output
[0, 1, 4, 9]

Generator expression uses () instead of [].

Key points

  • `yield` turns a function into a generator.
  • Lazy: values are produced on demand.
  • Memory-efficient for large data.
  • Generator expression: `(x for x in ...)`.
๐Ÿ’ก Note: You can iterate a generator only ONCE โ€” call the function again to get a fresh generator.

๐Ÿ“ Quick Quiz

1. The keyword that makes a generator is:

2. Generators are:

3. `(x*x for x in range(4))` is a: