UcenlyOpen in the app

Programming Essentials · BE5B33PRG · Topic 9 of 9

Comprehensions, iterators and generators

Express simple transforms and understand lazy iteration.

Open the interactive lesson

Key ideas

Comprehension

[x * x for x in range(5) if x % 2 == 0] gives [0, 4, 16]. Keep long logic in an ordinary loop.

Iterator

iter(items) creates an iterator; next(it) requests its next value. Exhaustion raises StopIteration. (Extra note beyond the lecture slides.)

Generator

A function with yield pauses and resumes, producing values on demand instead of a full list.

In one line: Choose a generator when sequential values need not be stored together.

Sources

Written by Ucenly. Based on the BE5B33PRG course materials: