Lesson 3 of 10
Building a list from another list is so common that Python has dedicated syntax for it. First, the long way you already know:
numbers = [1, 2, 3, 4]
doubled = []
for n in numbers:
doubled.append(n * 2)
print(doubled)
Four lines to say "double everything." A list comprehension says the same thing in one:
numbers = [1, 2, 3, 4]
doubled = [n * 2 for n in numbers]
print(doubled)
The shape
[ expression for item in sequence ]
Read it right to left: "for each item in sequence, compute expression, and collect the
results into a new list."
squares = [n ** 2 for n in range(1, 6)]
print(squares)
words = ["apple", "banana"]
upper = [w.upper() for w in words]
print(upper)
Adding a filter
Put an if at the end to keep only some items.
[ expression for item in sequence if condition ]
numbers = range(1, 11)
evens = [n for n in numbers if n % 2 == 0]
print(evens)
That reads as "give me n, for each n in numbers, if n is even." The equivalent loop needs
four lines and an append.
You can transform and filter at once:
numbers = range(1, 11)
big_squares = [n ** 2 for n in numbers if n > 7]
print(big_squares)
When not to use one
Comprehensions are for building a list. If you are not building a list — say you just want to
print each item — use a normal for loop. This works but is bad style:
[print(n) for n in range(3)]
It builds a throwaway list of None values as a side effect. Just write the loop.
The other limit is readability. If the comprehension needs multiple conditions and a nested loop, it stops being clearer than the loop it replaced. One transformation plus at most one filter is the sweet spot.
Try it yourself
From the numbers 1 to 10, build a list of the squares of the even numbers only.
Checkpoint
[expr for item in seq]builds a new list in one line.- Add
if conditionat the end to filter. - Comprehensions replace the build-an-empty-list-then-append pattern.
- Use a plain loop when you aren't building a list, or when the logic gets complex.
Questions about this lesson
Log in to ask a question.