Learn Python · lesson 53 of 60 · about 8 minutes
List Comprehensions
Build a new list from an old one in a single readable line.
What you'll learn
- Write a list comprehension
- Filter items with if
- Choose between a comprehension and a loop
Sam's steps
Sam's watch counts steps, and Sam wants the assistant to sum up the week. Sam types each day's steps on one line, like 8200 12500 lots 10300 4000, and the assistant keeps the whole numbers, shows them in thousands, [8, 12, 10, 4], and picks out the days that reached 10000. Each of those is a new list made from an old one, and Python has a short way to write that.
A loop in one line
You've often written loops that build a new list:
squares = [] then for n in nums: and squares.append(n * n).
A list comprehension does the same in one line: [n * n for n in nums]. Read it as "n times n, for each n in nums".
Same result, less code
nums = [1, 2, 3, 4]
squares = []
for n in nums:
squares.append(n * n)
print(squares)
print([n * n for n in nums])Output
[1, 4, 9, 16]
[1, 4, 9, 16]Keeping only some items
Add if at the end to keep only the items that pass a test: [n for n in nums if n % 2 == 0] keeps the even numbers. The part before for can be any expression, like a method call on each word.
Filtering and changing
words = ["tea", "Code", "phoebe", "Go"]
print([w for w in words if len(w) > 2])
print([w.upper() for w in words if w[0].isupper()])Output
['tea', 'Code', 'phoebe']
['CODE', 'GO']The filter runs first
In [int(s) for s in walk_text if s.isdigit()], the if is checked before the part at the front, so int() only ever sees text that is a whole number. A word like lots is dropped before anything tries to turn it into a number, and the assistant can't crash on it.
Tip
Comprehensions are great for short, simple transformations. If you need several steps, prints or nested ifs, a normal loop is easier to read.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.