Comprehensions
Build lists, sets, and dictionaries quickly from iterable values.
Build a list in one expression
A list comprehension creates a list by transforming each item in an iterable. It is a compact form of a for loop.
numbers = [1, 2, 3, 4] squares = [number * number for number in numbers] even_squares = [number * number for number in numbers if number % 2 == 0] print(squares) print(even_squares)
Read the expression from left to right: make a value, loop over items, then optionally keep only items that pass an if condition.
Compare a loop with a comprehension
| Equivalent for loop | List comprehension |
|---|---|
| squares = [] for n in numbers: squares.append(n * n) | squares = [n * n for n in numbers] |
pairs = [(row, column) for row in [1, 2] for column in ['A', 'B']] print(pairs)
With two for parts, the rightmost loop runs fully for each value from the first loop. This creates every row-and-column pair.
Other comprehension types
words = ['ant', 'bee', 'ant']
lengths = {word: len(word) for word in words}
first_letters = {word[0] for word in words}
steps = (number * 10 for number in range(3))
print(lengths)
print(sorted(first_letters))
print(list(steps))
Use braces with key: value for a dictionary comprehension and braces without a colon for a set comprehension. Parentheses make a generator expression, which produces values as you use them instead of storing a full list first.
Key points
- A list comprehension creates a list from an iterable.
- Add an if condition to filter items.
- Multiple for parts can create combinations.
- Dictionary and set comprehensions use braces.
- A generator expression produces values one at a time.
Worked example
Convert a week of taka amounts to dollars at rate 110 in one expressive line.
taka = [110, 220, 330] usd = [round(amount / 110, 2) for amount in taka] print(usd)
How it works, step by step
- Read it as: 'new list of round(amount/110, 2), FOR each amount in taka'.
- The expression at the front runs once per item.
- The result is a brand-new list; the old one is untouched.
References & Further Reading
Related entries from PyLabs's own reference library.
- map() (Apply a function to each item in one or more iterables.)
- filter() (Keep items that pass a test.)
- enumerate() (Pair each item with a counter.)
Practice exercise
Not passed yetUse a list comprehension to make doubled from numbers = [2, 3, 4], with every number multiplied by 2. Print doubled.
Expected output: [4, 6, 8]
# Write your code below
Check yourself
Comprehensions quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.