Cover by Francesco Cesarini, Simon Thompson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

List Comprehensions

Typical of operations on lists are mapping—applying a function to every element of a list—and filtering—selecting those elements of a list that have a particular property. Often these are used together, and the list comprehension notation gives you a powerful and compact way to write down lists constructed in this way. We’ll begin with some simple examples, and then look in more detail at a simple database case study.

A First Example

The list comprehension in the following code has the generator X <- [1,2,3], which means X runs through the values 1, 2, and 3 in turn. Going into the output for each of these is X+1, the expression before the symbol ||, 1 leading to 2, and so on. This gives the result [2,3,4].

1> [X+1 || X <- [1,2,3]].
[2,3,4]

In the next code snippet, there is a filter, X rem 2 == 0, which selects only those Xs that pass this test. Here, that X is even:

2> [X || X <- [1,2,3], X rem 2 == 0].
[2]

The following code combines the two: the even elements of [1,2,3] are selected, and 1 is added to each of them.

3> [X+1 || X <- [1,2,3], X rem 2 == 0].
[3]

These are the basics of list comprehension. Next, we’ll discuss what a list comprehension is like in general, before looking at a larger example.

General List Comprehensions

In general, a list comprehension has three component parts:

[ Expression || Generators, Guards, Generators, ... ]
Generators

A generator has the form Pattern <- List, where Pattern is a pattern that is matched with elements from the List expression. ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required