Comprehensions are concise and expressive syntax constructs in Julia to create arrays or other iterable objects by applying an operation to each element of an existing iterable, often while filtering elements based on a condition. Comprehension makes our code code more readable and efficient.
This concept, despite its somewhat unusual name, is essentially a method for creating and gathering items. In more formal mathematical terms, you might express it as follows:
"Let S be the set of all elements n where n is greater than or equal to 1 and less than or equal to 10"
In Julia, we can write this as:
[operation(n) for n in 1:10]
Here, operation(n)
is the operation or function we want to perform on every value of n
, 1:10
represents the range. The construction [operation(n) for n in 1:10]
is called array comprehension or list comprehension.
The syntax for Julia’s array comprehensions is as follows:
[operation for n = iterable]
Essentially, the above expression is equivalent to creating an empty array and using a for
loop to push!
items to it.
output = []for n in iterablepush!(output, operation)end
Array comprehensions create arrays by performing an operation on each iterable element and collecting the results in a new array. The basic syntax is as follows:
[operation(item) for item in iterable]
Here, operation(item)
is the operation or function we want to perform on every value of item
. While iterable
represents a collection of items that we can loop through, such as a list or range.
Let’s demonstrate the use of array comprehensions:
cube = [x^3 for x in 1:10]println(cube)
Line 1: It creates a list comprehension in Julia. It generates a list called cube
by applying the cube operation (raising to the power of three) to each element x
in the range from one to ten.
Line 2: It prints the contents of the cube
list, which will display the cube of numbers from one to ten.
Free Resources