Lesson 11 of 55
9 mins readPython Array & Generator Comprehensions
In Plain English
Array comprehensions provide a clean mathematical notation [f(x) for x in coll if cond] for creating new arrays and multi-dimensional matrices in a single line.
Deep Dive: How It Works
1D Comprehensions: [x^2 for x in 1:5] constructs [1, 4, 9, 16, 25].
Filtering with if: [x for x in 1:10 if iseven(x)] filters elements while building the array.
2D Matrix Comprehensions: [i * j for i in 1:3, j in 1:3] constructs a 3x3 Matrix.
Generator Expressions: (x^2 for x in 1:100) creates a lazy iterator without allocating memory for the whole array.
Core Rules to Remember

Mathematical Set-Builder Notation: Clean syntax for mapping, filtering, and constructing vectors and matrices.

Zero Allocation Generators: Use parentheses (x for x in coll) for lazy streams without memory allocation.
Live Interactive Example
Hit Run Code to see it liveArray and Matrix Comprehensions
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: [x^2 for x in 1:10 if iseven(x)] filters evens then squares them.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Create Cube Comprehension
Create an array `cubes = [x^3 for x in 1:5]`.
Print `"Cubes: "` followed by `cubes`.
1
2
3
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.