List comprehensions
🌍 In real life. A juice stall's press takes in fruit after fruit and pushes out a glass for each one. You don't describe every glass; you describe the recipe once ("one glass of juice for each orange in the basket") and the press does the rest.
A list comprehension is that recipe: one line that says what each new item is and where the items come from.
The idea in one sentence: [expression for name in source] builds a new list with one item, the expression, for each item of the source.
Its words:
- comprehension: a one-line way to build a list from another sequence
- expression: what goes into the new list, like
n * n - source: what the loop walks through, like
range(1, 5)or a list
Step by step, for [n * n for n in range(1, 5)]:
- n is 1: the expression
n * nis 1, so 1 goes in. - n is 2, 3, 4: 4, 9 and 16 go in.
- The finished list is
[1, 4, 9, 16].
Read it as "make a list of expression, for each name in source".
squares = []
for n in range(1, 5):
squares.append(n * n)
print(squares)
squares = [n * n for n in range(1, 5)]
print(squares)words = ["hi", "yo", "hey"]
print([w.upper() for w in words])
print([len(w) for w in words])A favourite trick: turn a whole line of input into numbers at once.
nums = [int(w) for w in input("Numbers: ").split()]
print(nums)
print(sum(nums))How Python does it, and what it costs. A comprehension runs exactly like the loop-and-append version: one lap per item of the source, so the same amount of work. It's a little faster in practice, because Python doesn't have to look up .append on every lap, and it's easier to read when the job is "make a new list from an old one".
The loop variable lives only inside the brackets: after [n * n for n in range(3)], the name n doesn't exist outside.
Mistakes and edge cases.
- Using the loop variable afterwards.
print(n)after the comprehension givesNameError: name 'n' is not defined. - A comprehension just for its side effects.
[print(x) for x in items]works, but it builds a useless list ofNones. Use a normalforloop to do things; use a comprehension to make a list. - Squeezing too much in. If you need several lines of logic, a normal loop is clearer.
Quiz
What does this print?
print([x * 2 for x in [1, 2, 3]])What does this print?
print([len(w) for w in ["a", "bb", "ccc"]])What does this print?
print([c for c in "hi"])Which loop builds the same list as
[n + 1 for n in nums]?- out = [] then for n in nums: out.append(n + 1)
- for n in nums: n = n + 1
- out = nums + 1
Which line has a mistake?
nums = [1, 2, 3] doubled = [for n in nums: n * 2] print(doubled)
Coding tasks
Ask for whole numbers on one line. Print a list of their doubles, using a list comprehension.
Ask for some words on one line. Print a list of their first letters in capitals. For
apple banana, print['A', 'B'].Ask for a whole number
n. Print the list of squares from 1 × 1 up ton×n.