Journey

Iteration

This journey follows repeated work from ordinary loops to the iterator protocol: consume values, stop deliberately, and produce lazy streams only when they help.

In this journey

  • Choose the right loop shape.
  • See the protocol behind `for`.
  • Compose lazy value streams.

Choose the right loop shape.

Loops differ by what they consume, when they stop, and whether completion itself carries meaning.

stop ruleforexhaustedwhileconditionsentinelmarker
Choose the loop from its stopping rule: exhaustion, condition, or sentinel marker.
  • For Loops

    Use this example to consume values from an iterable.

  • While Loops

    Use this example to repeat while a condition must be rechecked.

  • Break and Continue

    Use this example to interrupt or skip loop work intentionally.

  • Loop Else

    Use this example to attach completion logic to loops that did not break.

  • Sentinel Iteration

    Use this example to show `iter(callable, sentinel)` for repeated reads until a marker appears.

See the protocol behind `for`.

The important mental shift is that loops consume producers through a protocol rather than special-casing lists.

forITERABLExsiter()ITERATORitnext()abStopIteration
for is surface syntax; iter() creates an iterator and next() pulls values until StopIteration.
  • Iterating over Iterables

    Use this example to separate value producers from value consumers.

  • Iterators

    Use this example to use `iter()` and `next()` to expose the protocol behind `for`.

  • Generators

    Use this example to write functions that produce values lazily.

Compose lazy value streams.

Iterator pipelines are useful when code can transform values one at a time instead of materializing every intermediate result.

sourcefiltermapvaluenext()no list
Lazy pipelines run from the consumer's pull: next() requests one value through each stage.
  • Generator Expressions

    Use this example to create lazy one-pass streams with expression syntax.

  • Itertools

    Use this example to compose iterator streams without materializing every value.

  • Yield From

    Use this example to delegate part of a generator to another iterable.