Skip to content

List Comprehensions

It is easy enough to generate lists using various list functions, such as unfoldr, repeat, replicate, and many more, but this is not as convenient as it could be. If you have used Python before, then you will be used to list comprehensions, that is, formulas that generate lists. For example, here is a way to generate all even numbers between 1 and 10 in Python:

Python
>>> [x for x in range(1,11) if x % 2 == 0]
[2, 4, 6, 8, 10]

There are better ways to do this, but my point is to show you a list comprehension in Python. You can read this as the list of all values x in the range from 1, inclusive, to 11, exclusive, that satisfy the condition that x % 2 == 0, that is, that they are even. The corresponding Haskell comprehension looks fairly similar:

GHCi
>>> [x | x <- [1..10], even x]
[2,4,6,8,10]

Again, this says that we take all values x from the list [1..10], that is, the list of integers between 1 and 10 that satisfy the condition even x.

Since this isn't a course on Python, I won't explain the syntax for list comprehensions in Python in detail, but I will explain the syntax for list comprehensions in Haskell.