**1. What are list comprehensions?**

List comprehensions construct lists in natural-to-express ways. They can replace map-filter combinations and many for loops.

They’re just syntactic sugar. That means they make your code easier to read (and prettier).

**Example 1: For loops -> List comprehension**

1 2 3 4 5 6 7 8 9 10 11 12 |
# Make a list of squares of 1 to 10 >>> squares = [] >>> for i in range(1,11): ... squares.append(i**2) ... >>> squares [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # List comprehension >>> squares_lc = [i**2 for i in range(1,11)] >>> squares_lc [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] |

**Example 2: Map-filter -> List Comprehension**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Map and filter >>> doubled_odd_numbers = list(map( lambda n: n * 2, filter(lambda n: n % 2 == 1, range(1,10)) )) >>> doubled_odd_numbers [2, 6, 10, 14, 18] # List comprehension >>> doubled_odd_numbers_lc = [ n * 2 for n in range(1,10) if n % 2 == 1 ] >>> doubled_odd_numbers_lc [2, 6, 10, 14, 18] |

(I will do a post on map and filter and link to it here later.)

#### 2. Why might we use list comprehensions?

Because they’re more elegant (see above). That’s basically it.

The idea came from mathematics, where you may have seen sets constructed like this:

(Read: S is the set of all such that x is a positive integer between 1 and 10 inclusive.)

(Read: M is the set of x such that x is in S and x is even.)

Notice the parallels with the corresponding list comprehensions:

1 2 3 4 5 6 7 |
>>> s = [x**2 for x in range(1,10)] >>> s [1, 4, 9, 16, 25, 36, 49, 64, 81] >>> m = [x for x in s if x % 2 == 1] >>> m [1, 9, 25, 49, 81] |

#### 3. Understanding list comprehensions

Trey Hunner has an excellent animated, step-by-step tutorial on going from for loops to list comprehensions (and vice versa).

The way to get familiar with list comprehensions once you’ve understood what they are is through **practice**: attempting relevant problems and constantly asking yourself if you can replace your for loops or map-filter combos with list comprehensions. Sites like HackerRank or CodeWars are great for finding problems to practice on.

**4. Techniques**

**Technique 1: Nested loops**

You might have a for loop that looks like this:

1 2 3 4 5 6 7 8 9 |
# Flatten a matrix >>> matrix = [[1,2,3],[4,5,6],[7,8,9]] >>> flattened_matrix = [] >>> for i in range(3): ... for j in range(3): ... flattened_matrix.append(matrix[i][j]) ... >>> flattened_matrix [1, 2, 3, 4, 5, 6, 7, 8, 9] |

The corresponding list comprehension is

1 2 3 |
>>> fm_lc = [matrix[i][j] for i in range(3) for j in range(3)] >>> fm_lc [1, 2, 3, 4, 5, 6, 7, 8, 9] |

Is this what you expected? The order in which you list the clauses is the order in which you’d write the for loops if they were for loops, and not how you’d say them in plain English (which would be the other way round).

Let’s rewrite the list comprehension with line breaks in between to make it clearer:

1 2 3 4 5 6 7 |
>>> fm_lc = [ ... matrix[i][j] ... for i in range(3) ... for j in range(3) ... ] >>> fm_lc [1, 2, 3, 4, 5, 6, 7, 8, 9] |

**Example 3: Primes under 100**

Here is an interesting example where we use list comprehensions to get a list of all prime numbers smaller than 100.

1 2 3 4 5 6 7 8 9 10 11 12 13 |
# multiples of all primes less than sqrt(100) under 100 >>> no_primes =[ ... j ... for i in range(2,8) ... for j in range(i*2, 100, i) ... ] >>> primes = [ ... x ... for x in range(2,100) ... if x not in no_primes ... ] >>> primes [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] |

(Example taken from Python Course)

**Technique 2: zip(): dealing with two or more elements at a time.**

1 2 3 4 5 6 7 8 |
>>> first_names = ["Anna", "Betty", "Carol"] >>> last_names = ["X", "Y", "Z"] >>> full_names = [ ... "%s %s" % (f, l) ... for f, l in zip(first_names, last_names) ... ] >>> full_names ['Anna X', 'Betty Y', 'Carol Z'] |

**5. Tip: Improving Readability**

It’s important that your code is easily understandable by other people (and by yourself should you have to revisit it months later). List comprehensions make code more concise, but you can imagine that if you have many conditions or nested for loops, they can get messy fast. There are two points to note here:

1. If there are two many for or if clauses, split the list comprehension up into multiple list comprehensions.

2. If your list comprehension is long, insert line break between different clauses. (See `first_names`

, `last_names`

example, latter `no_primes`

example.)

#### 6. Related concepts

**Dict comprehensions and set comprehensions** (available in Python 3) are similar but are applied to dictionaries and sets.

Application: In our example constructing lists of prime numbers above, the list noprime contains duplicates. So if we wanted to remove the duplicates we could create a set instead.

- Resource: Python 3 Patterns has two nice examples of dict and set comprehensions. It also has a more technical exposition of comprehensions that explains them in terms of objects and predicates.