Generator Expression

Context: FIT1008_MOC · the lazy cousin of List Comprehension · produces an Iterator · consumes any Iterable

Quick Revision

  • 🎯 Objective: looks like a List Comprehension but with round brackets ➔ returns an Iterator producing elements on demand.
  • 📦 Core Components: lazy transform + filter, one element at a time ➔ sugar for a yield loop.
  • ⚡ Key Constraint: memory + short-circuit + infinite streams — but single-use, no len/indexing.

📝 Core

1. The Generator Expression (Lazy Comprehension)

  • Syntax ➔ same as a List Comprehension but round brackets ➔ returns an Iterator, not a list.
  • Lazy ➔ produces elements one at a time in memory.
  • Single-use ➔ no len, no indexing, can’t re-loop — once exhausted, rebuild.

2. Lazy Evaluation

  • Huge/infinite ➔ process unbounded sequences in memory ((line for line in open(f))).
  • Short-circuitany(p(x) for x in xs) stops at the first hit.
  • Pipeline fusion ➔ chain filter→map→reduce with no intermediate lists.
  • General formyield (a generator function = restricted coroutine); a genexp is sugar for a simple yield loop.

⚙️ Core Implementation

🔹 List vs generator

⚖️ Core Decision Matrix

List Comprehension [...]Generator (...)
returnsa list (all elements)an Iterator (one at a time)
memory
computedeagerlylazily, per next
re-iterate?yesno — single-use
len/indexing?yesno

When It Flips: generators win on memory + early-exit; lists win when you need random access, len, or to loop more than once. A genexp is equivalent to a yield-based generator function — both suspend at each yield and resume on next (a restricted coroutine).

📊 Exam Execution Trace

Manual Execution Trace

sum(x*x for x in range(4) if x%2):

Step / Statexx%2?x*xRunning sum
0 (Init)0
10no0
21yes11
32no1
43yes910

Streams filter→map→reduce with no intermediate list.

Applied Exercise

Problem: Show short-circuiting saves work. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: laziness lets any/next terminate early — unreachable for a materialised list.

🧠 Active Recall