Julia Language Array comprehension


Example

Basic Syntax

Julia's array comprehensions use the following syntax:

[expression for element = iterable]

Note that as with for loops, all of =, in, and are accepted for the comprehension.

This is roughly equivalent to creating an empty array and using a for loop to push! items to it.

result = []
for element in iterable
    push!(result, expression)
end

however, the type of an array comprehension is as narrow as possible, which is better for performance.

For example, to get an array of the squares of the integers from 1 to 10, the following code may be used.

squares = [x^2 for x=1:10]

This is a clean, concise replacement for the longer for-loop version.

squares = []
for x in 1:10
    push!(squares, x^2)
end