CS 200: List Comprehensions

Video:

See List Comprehensions from Socratica.

List comprehensions are consise ways of executing functions on lists (and sets and dicts). They are inspired by mathematical notation and the Haskell programming language.

In math, the common ways to describe lists (or sets, or tuples, or vectors) are:

  • S = {x² : x in {0 ... 9}}
  • V = (1, 2, 4, 8, ..., 2¹²)
  • M = {x | x in S and x even}
  • In other words, you'll find that the above definitions tell you the following:

    S is a sequence that contains values between 0 and 9 included, and each value is raised to the power of two.

    The sequence V, on the other hand, contains the value 2 that is raised to a certain power x. The power x starts from 0 and goes till 12.

    Lastly, the sequence M contains only the even elements from the sequence S.

    See https://www.datacamp.com/community/tutorials/python-list-comprehension

    Below we give examples of equivalent computations using iteration, map, and list comprehensions.

    Convert a string of digits into a list of digits.

    Convert a string of digits into a list of integers

    Convert a string of digits into a list of squares

    Convert a range of integers into a list of pairs (tuples) of integers and squares

    Convert a list of characters into a list of pairs (tuples) of indices and characters

    (No map version.)

    Filter a range of integers, selecting only the even ones

    Uses filter instead of map

    Uses if inside list comprehension.

    Filters range of integers, selecting the ones greater than 4

    reduce combines values in a list

    Generating prime numbers

    See https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

    noprimes contains duplicates. If we convert it to a set, we will eliminate the duplicates.

    Set comprehensions

    By using {} instead of [] we can create set comprehensions.

    We can create literal sets using {}

    Dictionary comprehensions

    End of list comprehension notebook