List Comprehension - Overview

Overview

Consider the following example in set-builder notation.

This can be read, " is the set of all numbers "2 times " where is an item in the set of natural numbers, for which squared is greater than ."

In this annotated version of the example:

  • is the variable representing members of an input set.
  • represents the input set, which in this example is the set of natural numbers
  • is a predicate function acting as a filter on members of the input set.
  • is an output function producing members of the new set from members of the input set that satisfy the predicate function.
  • brackets contain the expression
  • the vertical bar and the comma are separators.

A list comprehension has the same syntactic components to represent generation of a list in order from an input list or iterator:

  • A variable representing members of an input list.
  • An input list (or iterator).
  • An optional predicate expression.
  • And an output expression producing members of the output list from members of the input iterable that satisfy the predicate.

The order of generation of members of the output list is based on the order of items in the input.

In Haskell's list comprehension syntax, this set-builder construct would be written similarly, as:

s =, x^2 > 3 ]

Here, the list represents, x^2>3 represents the predicate, and 2*x represents the output expression.

List comprehensions give results in a defined order (unlike the members of sets); and list comprehensions may generate the members of a list in order, rather than produce the entirety of the list thus allowing, for example, the previous Haskell definition of the members of an infinite list.

Read more about this topic:  List Comprehension