Python Comprehensions, Iterators and Generators · Lesson 74 of 149

Python List Comprehensions

What you will learn

  • How to build a list in one expression: [expression for item in iterable]
  • How to turn a loop with append into a comprehension
  • Comprehensions over strings, ranges, zip and enumerate
  • Two for clauses and nested comprehensions (grids)
  • That the loop variable is local to the comprehension
  • When a plain loop is clearer

1. From a loop to a comprehension

In lesson 6.5 you built a new list by looping and calling append:

nums = [1, 2, 3, 4, 5]

squares = []
for n in nums:
    squares.append(n * n)
print(squares)
[1, 4, 9, 16, 25]

That takes three lines to say "the squares of these numbers". A list comprehension says it in one expression:

squares = [n * n for n in nums]
print(squares)
[1, 4, 9, 16, 25]

Read it from the left, as a sentence: "n times n, for each n in nums". It makes exactly the same list.

The pattern:

[ expression for item in iterable ]

Part In the example
the expression n * n: what each new item will be
the loop variable n
the iterable nums: anything you can loop over

To turn a loop into a comprehension: take the thing you append (the expression), and put it first, followed by the for line of the loop.

Quick check: what is `[n + 10 for n in [1, 2, 3]]`?

[11, 12, 13].

2. What you can loop over

Any iterable works: lists, strings, ranges, dictionaries, files, and the results of zip and enumerate:

print([c.upper() for c in "abc"])
print([i * 2 for i in range(5)])
print([len(w) for w in ["a", "bb", "ccc"]])
print([str(n) for n in nums])
print([abs(n) for n in [-1, 2, -3]])
['A', 'B', 'C']
[0, 2, 4, 6, 8]
[1, 2, 3]
['1', '2', '3', '4', '5']
[1, 2, 3]

The expression can be anything: arithmetic, a method call, a function call, a tuple, a conditional expression:

words = ["Apple", "banana", "Cherry"]
print([w.lower() for w in words])
print([w[0] for w in words])
print([(w, len(w)) for w in words])
print([f"{i}:{w}" for i, w in enumerate(words, 1)])
print([a + b for a, b in zip("ab", "xy")])
['apple', 'banana', 'cherry']
['A', 'b', 'C']
[('Apple', 5), ('banana', 6), ('Cherry', 6)]
['1:Apple', '2:banana', '3:Cherry']
['ax', 'by']

The last two use unpacking in the loop (lesson 8.2): i, w takes each pair from enumerate, and a, b each pair from zip.

A comprehension can also call your own functions, and convert data:

def double(n):
    return n * 2

print([double(n) for n in nums])
print([int(s) for s in "1 2 3".split()])
print([float(s) for s in ["1.5", "2"]])
[2, 4, 6, 8, 10]
[1, 2, 3]
[1.5, 2.0]

The first line is the same as list(map(double, nums)) (lesson 11.7), but most people find the comprehension easier to read.

3. Two for clauses

A comprehension may have more than one for. They act like nested loops, with the first for as the outer loop:

print([(x, y) for x in range(2) for y in "ab"])
print([x * y for x in range(1, 4) for y in range(1, 4)])
[(0, 'a'), (0, 'b'), (1, 'a'), (1, 'b')]
[1, 2, 3, 2, 4, 6, 3, 6, 9]

This is the same as:

result = []
for x in range(2):
    for y in "ab":
        result.append((x, y))

The for parts keep the same order as the nested loops, written left to right. That is the key to reading them.

Flattening a list of lists

matrix = [[1, 2, 3], [4, 5, 6]]
print([x for row in matrix for x in row])
[1, 2, 3, 4, 5, 6]

Read it as: "for each row in matrix, for each x in that row, take x". (Lesson 7.5 showed this.)

4. Nested comprehensions: grids

A comprehension can contain another comprehension as its expression. This builds lists of lists:

print([[0] * 3 for _ in range(2)])
print([[i * j for j in range(1, 4)] for i in range(1, 4)])
print([[x * 2 for x in row] for row in matrix])
print([sum(row) for row in matrix])
print([[row[i] for row in matrix] for i in range(3)])
[[0, 0, 0], [0, 0, 0]]
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]
[[2, 4, 6], [8, 10, 12]]
[6, 15]
[[1, 4], [2, 5], [3, 6]]
  • [[0] * 3 for _ in range(2)] builds a grid with separate rows, which avoids the shared-row trap of lesson 7.5.
  • [[i * j for j in range(1, 4)] for i in range(1, 4)] is a multiplication table: the inner comprehension makes a row, the outer one collects the rows.
  • The last line transposes the grid (swaps rows and columns).

Do not confuse the two shapes:

Written as Gives
[x for row in m for x in row] one flat list (two for in one comprehension)
[[x for x in row] for row in m] a list of lists (a comprehension inside a comprehension)

5. The loop variable is local

In Python 3, the variable of a comprehension is local to the comprehension. It does not leak out and it does not disturb a variable of the same name outside (lesson 11.5):

sq = [k * k for k in range(3)]
print(k)
NameError: name 'k' is not defined
k = "outer"
tmp = [k for k in range(2)]
print(k, tmp)
outer [0, 1]

(A for loop, by contrast, leaves its variable behind after it ends.)

6. A new list, every time

A comprehension always builds a brand-new list. The original is untouched:

old = nums
nums = [n + 1 for n in nums]
print(old)
print(nums)
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]

To change a list in place, use lst[:] = [... for ...] (lesson 7.3). Otherwise, you assign the new list to a name.

7. Speed

A comprehension is usually a little faster than the equivalent loop with append, because Python runs it with less work per item. In a test with 1000 numbers on one computer, the comprehension was faster than the loop with append. The saving is small, so choose by readability first. When speed matters, measure your own code with timeit (lesson 18.5).

8. When not to use one

A comprehension is for building a list. A plain loop is better when:

  • you do not want the list (you only want a side effect such as printing). Never write [print(x) for x in items]: it builds a useless list of None.
  • the logic needs several statements, an else, or error handling.
  • the comprehension has too many parts. A good limit is one for and one if. Two for clauses are fine if short. Three levels are very hard to read.

Split a long one over several lines, one clause per line:

names = [
    w.strip().title()
    for w in [" rina ", "SAM", "lee  "]
]
print(names)
['Rina', 'Sam', 'Lee']

If it still looks heavy, write a loop, or put part of it in a named function. Readable code is worth more than a short line.

Worked example: report lines from records

Turn a list of (name, mark) records into report lines, extract the marks, and build a table of the marks doubled for a bonus round.

records = [("Rina", 72.5), ("Sam", 64), ("Lee", 91.25)]

lines = [f"{i}. {name:<5} {mark:>6.1f}" for i, (name, mark) in enumerate(records, 1)]
marks = [mark for _, mark in records]
initials = [name[0] for name, _ in records]
bonus = [[name, mark * 2] for name, mark in records]

print("\n".join(lines))
print(marks)
print(initials)
print(bonus)
print(round(sum(marks) / len(marks), 2))
1. Rina    72.5
2. Sam     64.0
3. Lee     91.2
[72.5, 64, 91.25]
['R', 'S', 'L']
[['Rina', 145.0], ['Sam', 128], ['Lee', 182.5]]
75.92

Notice that 91.25 is shown as 91.2: the format .1f rounds a tie to the even digit (lesson 3.3).

Comprehension What it builds
lines formatted text lines, numbered with enumerate and unpacked as (name, mark)
marks the numbers only, ignoring the names with _
initials the first letter of each name
bonus a list of lists

The records are made up. (:<5 and :>6.1f are format codes from lesson 4.6.)

Common mistakes

  • Using a comprehension just for side effects ([print(x) for x in items]).
  • Putting the for first. The expression comes first: [n * n for n in nums].
  • Mixing up flat and nested shapes (two for clauses against a comprehension inside one).
  • Writing very long or deeply nested comprehensions.
  • Expecting the comprehension to change the original list. It builds a new one.
  • Forgetting that [0] * 3 inside a comprehension is safe for numbers, but [[]] * 3 is not.

Key takeaways

  • [expression for item in iterable] builds a new list; read it as a sentence from the left.
  • Take the loop's append argument as the expression and put it first.
  • Several for clauses act like nested loops in the same order; a comprehension inside a comprehension makes a grid.
  • The loop variable is local to the comprehension, and the original data is never changed.
  • Use a comprehension to build a list; use a loop for side effects or complicated logic.

Practice

1. Write a comprehension for the cubes of 1 to 5.

Show answer

[n ** 3 for n in range(1, 6)] gives [1, 8, 27, 64, 125].

2. Turn [w.upper() for w in words] into a loop.

Show answer
result = []
for w in words:
    result.append(w.upper())

3. Make the list of the lengths of the words in ["tree", "sky", "mountain"].

Show answer

[len(w) for w in ["tree", "sky", "mountain"]] gives [4, 3, 8].

4. Write a comprehension that flattens [[1, 2], [3], [4, 5]].

Show answer

[x for row in [[1, 2], [3], [4, 5]] for x in row] gives [1, 2, 3, 4, 5].

5. Why is [print(n) for n in nums] poor style?

Show answer

It builds a list of None values that nobody uses. A comprehension is for building a list; use a plain for loop to print.

6. Build a 3 by 3 grid of zeros with separate rows.

Show answer

[[0] * 3 for _ in range(3)].