Julia Comprehensions Tutorial
last modified November 18, 2026
A comprehension is a compact expression that builds a collection by evaluating an expression for each element of an iterator. It replaces a loop that creates an empty array and pushes values into it with a single readable line. Julia supports comprehensions for arrays and dictionaries, plus generator expressions that produce values lazily.
This tutorial covers array comprehensions, filters, nested and multidimensional
loops, dictionary comprehensions, generators, typed results, and flattening with
Iterators.flatten. A basic example appears in
Julia arrays; here each form is examined in detail.
All examples were verified with Julia 1.13.4.
Array Comprehensions
An array comprehension is written with square brackets. Inside them, an
expression is followed by a for clause that names the loop variable
and the iterator it draws from.
squares = [x^2 for x in 1:5] println(squares) println(typeof(squares))
The expression x^2 is evaluated for each value in the range 1 to 5,
and the results form a vector of five integers. The type is
Vector{Int64}, the standard one-dimensional array of integers.
Ranges are explained in Julia ranges.
$ julia main.jl
[1, 4, 9, 16, 25]
Vector{Int64}
Iterating Over Other Collections
The iterator in a comprehension need not be a range. Any iterable works, including strings and tuples.
println([uppercase(c) for c in "abc"])
println([length(w) for w in ("one", "two", "three")])
The first comprehension walks over the characters of the string and uppercases
each one, giving an array of Char values. The second iterates over a
tuple of words and records each word's length: 3, 3, and 5. Iteration is covered
in Julia iterators.
$ julia main.jl ['A', 'B', 'C'] [3, 3, 5]
Filtering with if
An if clause at the end of a comprehension keeps only the elements
that satisfy a condition. Several conditions can be joined with the logical
operators seen in Julia operators.
println([x for x in 1:10 if iseven(x)]) println([x for x in 1:10 if x % 2 == 0 && x > 4])
The first line selects the even numbers from 1 to 10. The second adds a second
condition with &&, keeping only even numbers greater than 4.
The output arrays are therefore [2, 4, 6, 8, 10] and
[6, 8, 10].
$ julia main.jl [2, 4, 6, 8, 10] [6, 8, 10]
Nested Loops
A comprehension can contain more than one for clause. They are read
from left to right, like nested loops, and the expression is evaluated once for
every combination.
println([i*j for i in 1:3 for j in 1:3])
The outer variable i changes slowest and j changes
fastest, so the nine products appear in the order 1, 2, 3, then 2, 4, 6, then 3,
6, 9. Because both loops are written in one comprehension, the result is a flat
vector of nine elements.
$ julia main.jl [1, 2, 3, 2, 4, 6, 3, 6, 9]
Multidimensional Comprehensions
Separating the loop variables with a comma instead of repeating for
produces a multidimensional array. A comma builds a matrix, while a second
for keeps the result flat.
m = [i + j for i in 1:3, j in 1:3] println(m) println(size(m))
The result is a 3 by 3 matrix whose entries are the sums of the row and column
indices. The size function confirms the two dimensions. Matrices and
other multidimensional arrays are covered in Julia
arrays.
$ julia main.jl [2 3 4; 3 4 5; 4 5 6] (3, 3)
Dictionary Comprehensions
A dictionary comprehension uses Dict(key => value for ...). Each
iteration must produce a pair, written with the => operator.
d = Dict(x => x^2 for x in 1:3) println(d) println(d[3]) println(typeof(d))
The dictionary maps each integer to its square, so looking up 3 gives 9 and the
type is Dict{Int64, Int64}. A dictionary is unordered, so the order
in which the pairs are printed is not significant. Dictionaries are introduced in
Julia dictionaries.
$ julia main.jl
Dict(3 => 9, 2 => 4, 1 => 1)
9
Dict{Int64, Int64}
Generator Expressions
A generator expression looks like a comprehension without the square brackets.
It does not build an array; instead it yields values one at a time to a
consuming function such as sum or collect.
println(sum(x^2 for x in 1:5)) println(collect(x^2 for x in 1:3))
The first line adds the squares of 1 through 5 and prints 55 without ever
creating an intermediate array. Calling collect on a generator does
build an array, here [1, 4, 9]. Generators are a lightweight way to
feed data into reductions.
$ julia main.jl 55 [1, 4, 9]
Typed Comprehensions
Placing a type before the square brackets converts the result to an array of that element type. This is useful when a smaller numeric type is wanted.
a = Int8[x for x in 1:3] println(a, " ", typeof(a))
The values are the same as in an ordinary comprehension, but the array is a
Vector{Int8} rather than Vector{Int64}. Julia prints the
type prefix before the elements to make the distinction visible. Numeric types are
described in Julia data types.
$ julia main.jl
Int8[1, 2, 3] Vector{Int8}
Conditional Expressions
The expression at the start of a comprehension can be any expression, including a ternary conditional. This lets each element be transformed differently.
println([x % 2 == 0 ? x : -x for x in 1:4])
Even numbers are kept as they are and odd numbers are negated, giving
[-1, 2, -3, 4]. A filtering if chooses which elements
appear, while a conditional expression chooses what each element becomes.
$ julia main.jl [-1, 2, -3, 4]
Flattening Nested Collections
Sometimes a comprehension produces a collection of collections that should be
joined into one sequence. Iterators.flatten walks the inner
collections one after another, and collect turns the result into an
array.
println(collect(Iterators.flatten([[1, 2], [3, 4], [5]])))
The input is a vector of three vectors. Flattening removes one level of nesting,
so the result is the single vector [1, 2, 3, 4, 5]. This is handy
when several comprehensions each produce a list that must be combined.
$ julia main.jl [1, 2, 3, 4, 5]
Comprehensions Producing Tuples
The expression can also construct a tuple from the loop variables, which is a convenient way to enumerate all pairs from two collections.
println([(i, j) for i in 1:2 for j in 1:2])
Each iteration produces a pair inside parentheses. The four tuples appear in
nested-loop order: (1, 1), (1, 2), (2, 1),
and (2, 2). Tuples are described in Julia
tuples.
$ julia main.jl [(1, 1), (1, 2), (2, 1), (2, 2)]
Best Practices for Comprehensions
A few guidelines keep comprehensions clear and efficient.
- Use comprehensions for transformations: they express a map or filter more clearly than a hand-written loop.
- Use generators for reductions: pass
sum(x for x in ...)instead of building an array first. - Remember the comma distinction: a comma between loop variables
makes a matrix; a second
formakes a flat vector. - Keep expressions short: move complicated logic into a named function to keep the comprehension readable.
Source
Julia Comprehensions documentation
Julia Generator Expressions documentation
In this article we have worked with comprehensions in Julia: array and dictionary forms, filters, nested and multidimensional loops, generators, typed results, conditional expressions, flattening, and tuple results. Arrays are covered in Julia arrays, iteration in Julia iterators, and ranges in Julia ranges.
Author
List all Julia tutorials.