Skip to content

Comprehensions

Build lists, sets, and dictionaries quickly from iterable values.

12 min read 10 quiz questions

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.

Example 1: basic and filtered list comprehensions
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 loopList comprehension
squares = [] for n in numbers: squares.append(n * n)squares = [n * n for n in numbers]
Example 2: nested loops in a comprehension
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

Example 3: dictionary, set, and generator expressions
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.

Example
taka = [110, 220, 330]
usd = [round(amount / 110, 2) for amount in taka]
print(usd)

How it works, step by step

  1. Read it as: 'new list of round(amount/110, 2), FOR each amount in taka'.
  2. The expression at the front runs once per item.
  3. 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.)

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Practice exercise

Not passed yet

Use 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
Want another challenge on this module? More coding practice

Check yourself

Comprehensions quiz

10 questions. You get instant feedback per question, and the timer starts when you press the button.

Lesson incomplete

Not completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/5 complete
Module cheat sheet