liveBook · Manning

Lazy evaluation

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A lazy function defers producing a result until that result is needed.

Lazy evaluation defers producing values until a program needs them. Python's range(), reversed(), map(), and filter() return lazy results rather than immediately building complete lists. section 10.1.3 section 14.5

Use a consumer when you need to force or traverse a lazy result:

  • Call list() in the REPL to materialize values, such as list(range(0, 44)). section 10.1.3
  • Iterate directly with a for loop; range() supplies indexes as the loop requests them. section 10.1.3
  • Wrap reversed(range(1, 5)) in list() to inspect [4, 3, 2, 1]. section 11.1.1
  • Consume map() or filter() with join(), a loop, or list(); filter() returns only elements accepted by its function. section 14.3.1 section 14.5

Inspecting deferred values

>>> range(len('The quick brown fox jumps over the lazy dog.')) range(0, 44) >>> list(range(len('The quick brown fox jumps over the lazy dog.'))) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43] section 10.1.3

Filtering without an eager list

>>> cars = ['blue Honda', 'red Chevy', 'blue Ford'] >>> list(filter(lambda car: car.startswith('blue '), cars)) ['blue Honda', 'blue Ford'] The filter() computation remains lazy until list() requests its results; a list comprehension expresses the same selection more directly. section 14.3.1

>>> list(reversed(range(1, 5)))
[4, 3, 2, 1]

Shows a concrete reversed() result after list() forces the lazy sequence. section 11.1.1

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines deferral and demonstrates materialization with list(), but stops short of implementation internals.
Examples
Demonstrates character indexes, reverse counting, consonant filtering, car selection, and vowel replacement.
What you can do after
Apply it via Python's list(), loops, join(), map(), and filter() to control when iterable results are produced.
How it connects
Connects lazy evaluation with iterables, range(), reversed(), map(), filter(), list comprehensions, and higher-order functions.

Also explained in

Compare how 13 books explain lazy evaluation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.