Julia Comprehensions & Generators
A comprehension builds an array from an expression and one or more loops, all inside square brackets. It's a compact, readable and fast way to create arrays.
squares = [x^2 for x in 1:6]
println(squares)
names = ["ada", "alan", "grace"]
println([uppercase(n[1]) * n[2:end] for n in names])
println([x for x in 1:20 if x % 6 == 0]) # with a filter
println([iseven(n) ? "even" : "odd" for n in 1:3])[1, 4, 9, 16, 25, 36]
["Ada", "Alan", "Grace"]
[6, 12, 18]
["odd", "even", "odd"]
The general form is [expression for variable in collection if condition]; the if part is optional.
Multi-dimensional comprehensions
Two loops separated by a comma produce a matrix: the first loop indexes rows, the second columns.
table = [i * j for i in 1:3, j in 1:4]
println(size(table))
for row in eachrow(table)
println(join(lpad.(row, 3)))
end
dist = [abs(i - j) for i in 1:4, j in 1:4]
println(dist)(3, 4)
1 2 3 4
2 4 6 8
3 6 9 12
[0 1 2 3; 1 0 1 2; 2 1 0 1; 3 2 1 0]
If you write the loops with for ... for ... (no comma) instead, you get a flat vector with the later loop varying fastest — and the later loop may depend on the earlier variable:
pairs_list = [(i, j) for i in 1:3 for j in i:3]
println(pairs_list)
triples = [(a, b, c) for c in 1:15 for b in 1:c for a in 1:b if a^2 + b^2 == c^2]
println(triples)[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
[(3, 4, 5), (6, 8, 10), (5, 12, 13), (9, 12, 15)]
Typed comprehensions
Prefix the brackets with a type to fix the element type:
v = Float64[n for n in 1:3]
println(v, " ", typeof(v))
labels = String["item$i" for i in 1:2]
println(labels)[1.0, 2.0, 3.0] Vector{Float64}
["item1", "item2"]
Dictionary and set comprehensions
Wrap a generator of pairs in Dict(...) or of values in Set(...):
words = ["apple", "fig", "banana"]
lengths = Dict(w => length(w) for w in words)
println(lengths["banana"], " ", length(lengths))
initials = Set(first(w) for w in words)
println(sort(collect(initials)))6 3
['a', 'b', 'f']
Generators
Writing a comprehension with parentheses (or directly as a function argument) creates a generator: a lazy object that produces values one at a time without storing them in an array. This saves memory when you only need to reduce the values:
gen = (x^2 for x in 1:4)
println(typeof(gen) <: Base.Generator)
println(collect(gen))
println(sum(x^2 for x in 1:1000)) # no temporary array
println(maximum(length(w) for w in ["hi", "hello", "hey"]))
println(any(x > 100 for x in (3, 50, 120)))
println(join((string(c, c) for c in "abc"), "-"))true
[1, 4, 9, 16]
333833500
5
true
aa-bb-cc
sum(x^2 for x in 1:1000) computes the result without ever building a 1000-element array.
Tip: When the result is fed straight into
sum,maximum,any,join, etc., drop the brackets and use a generator. When you need the array itself (to index it or reuse it), use a comprehension.
Test yourself
What does [x for x in 1:10 if x % 4 == 0] produce?
- [4, 8]
- [0, 4, 8]
- [true, false, ...]
- [4, 8, 12]
What is the shape of [i + j for i in 1:2, j in 1:5]?
- A 10-element vector
- A 2×5 matrix
- A 5×2 matrix
- A tuple
What is the main advantage of sum(x^2 for x in v) over sum([x^2 for x in v])?
- It gives a different result
- It avoids allocating a temporary array
- It sorts the values first
- It runs in parallel