Skip to main content
Module 6 · Lesson 3 of 423/36 in the course~14 min
Module lessons (3/4)

Generator expressions

Lesson preview5 hands-on exercises readyPython Course · Module 6 — Comprehensions and iteration

(... for ... in ...) syntax for lazy iteration, constant memory, and sum/any/all over streams.

What you'll learn in this lesson

  • Distinguish between list comprehension eager (O(N) RAM) and generator expression lazy (O(1) RAM).
  • Directly pass generator expression to reducers (sum, any, all, max, min, join) omitting redundant double parentheses.
  • Understand on-demand evaluation and the fact that a generator runs out after a single traversal (StopIteration).

Overview

A generator expression replaces the square brackets [...] of a list comprehension with parentheses (...). The result changes radically: instead of calculating and saving all the values in memory immediately, Python creates a lazy iterator (lazy) that calculates only one value at a time on request (O(1) memory).

If you need to add the squares of a million numbers, a list [x * x for x in range(10**6)] allocates millions of objects in the heap and then throws them immediately after the addition. A sum(x * x for x in range(10**6)) generator, on the other hand, produces one number at a time, adds it and discards it instantly using a few dozen constant bytes!

Sections covered in this lesson

  1. 1The mental model: just-in-time factory vs complete warehouse
  2. 2Clean and short-circuit syntax of any / all
  3. 3Quick check
  4. 4Test yourself
Pro Lesson · Module 6 — Comprehensions and iteration

Unlock "Generator expressions" and the full Python Course curriculum

(... for ... in ...) syntax for lazy iteration, constant memory, and sum/any/all over streams.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Python Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.