Julia Language Comprehensions Array comprehension

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Julia Language Question?