GENERATOR
is an expression that specifies how the elements of the new lists should be calculated, the ELEMENT
is an element from the specified LIST
, and the GUARD
is an optional condition we can set that an ELEMENT must satisfy to be considered for the new list we are creating. The whole line can be read as "create a list by applying the GENERATOR
for each ELEMENT
of the LIST
that meets the criteria set by the GUARD
". Let's take a look at an example list comprehension that creates a list of only even numbers:x
is an element of the list [1..10]
and x
is an even number". This simply puts x
into a new list if it meets the guard criteria, but we could also apply some function to x
:x
as it is in the list for our generator, but just use it to make sure it passes the guards check:['a'..'b']
is iterated through three times, once for each element in the first list [1..3]
.