Lesson 5 of 5 · Collections · 2 min read · Updated

Comprehensions

Building a new list, set or dictionary from another in a single readable line.

A very common loop builds a new list from an old one. A comprehension says the same thing in one line: what each item becomes, where it comes from, and optionally which items to keep.

python
squares = [n * n for n in range(1, 6)]
print(squares)

evens = [n for n in range(1, 11) if n % 2 == 0]
print(evens)

names = ["priya", "arun"]
print([name.title() for name in names])
Output
[1, 4, 9, 16, 25]
[2, 4, 6, 8, 10]
['Priya', 'Arun']

Example

Read [n * n for n in range(1, 6)] aloud: "n times n, for each n in 1 to 5". The same as four lines: an empty list, a for loop, and append.

Choosing a value

python
marks = [72, 45, 91]
print(["Pass" if m >= 50 else "Fail" for m in marks])
Output
['Pass', 'Fail', 'Pass']

Note where each if goes. An if at the end filters — some items are dropped. An if ... else at the front chooses — every item stays, but becomes one of two values.

Dictionary and set comprehensions

python
prices = {"idli": 30, "dosa": 55}
with_tax = {dish: round(p * 1.05, 2) for dish, p in prices.items()}
print(with_tax)

lengths = {len(w) for w in ["hi", "hello", "yo"]}
print(lengths)
Output
{'idli': 31.5, 'dosa': 57.75}
{2, 5}

Warning

Comprehensions are for building a collection. If a line gets hard to read — two loops and a condition, say — write an ordinary loop. Clear beats clever.

What does [x for x in [1, 2, 3, 4] if x > 2] give?

Try this now

  1. From a list of words, build a list of only the words longer than 4 letters, in capitals.
  2. Build a dictionary mapping each number from 1 to 10 to its cube.

Create a free account to save your progress, or sign in.