List Comprehension

Context: FIT1008_MOC · declarative syntax over filter for building a list · eager sibling of Generator Expression

Quick Revision

  • 🎯 Objective: build a new list with set-builder syntax [expr for x in iterable if cond] ➔ Python’s declarative map/filter.
  • 📦 Core Components: transform (expr) + optional filter (if) ➔ nests.
  • ⚡ Key Constraint: time, memory (materialises) — the generator is the -memory lazy alternative.

📝 Core

1. The Comprehension (Set-Builder Syntax)

  • Form[expr for x in iterable if condition] ➔ mirrors as [3*x for x in range(10)].
  • Declarative ➔ the alternative to map/filter (HOFs).
  • Materialises ➔ builds the whole list ( memory); body should be a pure-ish transform/filter — side-effecting comprehensions are an anti-pattern (use a loop).

⚙️ Core Implementation

🔹 Transform, filter, nest — and the three forms

⚖️ Core Decision Matrix

FormTimeSpaceWhen
list comprehensionneed the whole list, reused/indexed
Generator Expressionsingle pass / huge or infinite source
explicit for loopside effects, complex control flow

When It Flips: comprehensions are concise and faster than an equivalent append loop (C-optimised list-building) but materialise everything; deeply nested comprehensions hurt readability — fall back to loops.

📊 Exam Execution Trace

Manual Execution Trace

[x for x in range(6) if x % 2 == 0]:

Step / Statexx%2==0?Emit
0 (Init)[]
10, 2, 4yeskept
21, 3, 5nodropped
result[0, 2, 4]

Applied Exercise

Problem: Show a comprehension equals map∘filter. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: the comprehension is the eager, materialised form of the filter→map pipeline.

🧠 Active Recall