List Comprehension

Learn how to build lists using list comprehensions.

In the final lesson on lists, we take a look at another powerful syntactic element to build complex lists: the list comprehension syntax.

List comprehensions by example

List comprehensions are a concept inspired by set definitions in mathematical notation. In mathematics, the definition

{x2  xN,x is even}\{ x^2 \ |\ x \in \mathbb{N}, x \text{ is even} \}

defines the set of even squares. It is advised to start reading such a set definition from the right of the separating pipe symbol |.

  1. The elements xx are drawn from the set of natural numbers N\mathbb{N}.
  2. Only the even xx are kept.
  3. Finally (to the left of the pipe |), the set consists of the squares of these even xx.

Similarly, we can define a list of the even squares in Haskell by using the closely related list comprehension syntax.

Get hands-on with 1400+ tech skills courses.