Lesson 22 of 55
10 mins readPython List Comprehensions
In Plain English
List comprehensions provide an elegant syntax [output | input <- list, predicate] mirroring mathematical set-builder notation to map, filter, and combine collections.
Deep Dive: How It Works
Basic Comprehension: [x * 2 | x <- [1..5]] maps (* 2) over [1..5].
Predicates (Guards): [x | x <- [1..10], even x, x > 4] filters numbers.
Multiple Generators: [(x, y) | x <- [1, 2], y <- ["a", "b"]] produces the Cartesian product.
Core Rules to Remember

Mathematical Set-Builder Syntax: Declarative generation and filtering in a single expression.

Multiple Generators: Easily compute cartesian products and coordinate grids.
Live Interactive Example
Hit Run Code to see it livePythagorean Triples with Comprehensions
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Output Console
Click "Run Code" to view the rendered output.
How it works: 6^2 + 8^2 = 36 + 64 = 100 = 10^2, and 6 + 8 + 10 = 24.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Build Filtered Squares Comprehension
Generate `[x^2 | x <- [1..10], x > 5]`.
Print `"Result: "` followed by the result.
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.