🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Comprehensions

A comprehension builds an array by describing each value and where it comes from. One short expression replaces a loop that collects results.

One expression builds the whole array

The expression x * 2 is worked out for each value in the range. The results collect into a new array.

println([x * 2 for x in 1:4])

An if guard keeps only passing values

The guard tests each value from the range. Only the even values reach the result.

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

Two ranges make every pair

Two for parts act like nested loops over the two ranges. Each pair becomes a tuple in the result.

pairs = [(i, j) for i in 1:2 for j in 1:2]
for p in pairs
    println(p)
end

Example

squares = [n * n for n in 1:5]
big = [n * n for n in 1:5 if n > 3]
println(squares)
println(big)
println(length(squares))

Key points

  • Form: [expr for x in source] makes one value from expr for each x in the source.
  • Source: the source can be a range, a string, or an array.
  • Guard: an if part after the loop keeps only the rounds that pass the test.
  • Result: a comprehension always returns a new array.
  • Two inputs: two for parts run like nested loops and make one value per pair.

In this example, the first comprehension squares each number from 1 to 5. The second comprehension adds a guard, so only the squares for numbers above 3 are kept. The prints show all five squares, the two guarded squares, and the length 5.

Note

a comprehension collects values without assigning to an outside variable in a loop.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does [x + 1 for x in 1:3] give?