Comprehensions¶
In this tutorial, you will learn how to use comprehensions — a concise and expressive way to create lists, dictionaries, and sets in Python.
Time commitment: 15–20 minutes
Prerequisites:
- Python 3.12 or later installed on your machine
- Completed tutorials 01 through 04 (lists, tuples, dictionaries, and sets)
Learning objectives¶
By the end of this tutorial, you will be able to:
- Create lists using list comprehensions
- Filter items with conditional comprehensions
- Build dictionaries and sets with comprehensions
- Decide when to use a comprehension versus a loop
What are comprehensions?¶
A comprehension is a compact way to create a new collection by transforming and filtering items from an existing iterable. Instead of writing a multi-line loop, you can express the same logic in a single line.
List comprehensions¶
The basic syntax for a list comprehension is:
[expression for item in iterable]
Here is a simple example — creating a list of squares:
squares = [x ** 2 for x in range(1, 6)]
print(squares)
This is equivalent to the following loop:
squares = []
for x in range(1, 6):
squares.append(x ** 2)
print(squares)
Transformations¶
You can apply any expression to each item. For example, converting strings to uppercase:
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print(upper_words)
Filtering with conditions¶
Add an if clause to include only items that meet a condition:
[expression for item in iterable if condition]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
You can combine transformations and filtering in the same comprehension:
# Squares of even numbers only
even_squares = [n ** 2 for n in range(1, 11) if n % 2 == 0]
print(even_squares)
Dictionary comprehensions¶
Dictionary comprehensions use a similar syntax with curly braces and a colon separating keys from values:
{key: value for item in iterable}
words = ["apple", "banana", "cherry"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)
You can add conditions to dictionary comprehensions too:
scores = {"Alice": 85, "Bob": 42, "Charlie": 91, "Diana": 67}
# Only students who scored above 60
passing = {name: score for name, score in scores.items() if score > 60}
print(passing)
Set comprehensions¶
Set comprehensions use curly braces without the colon:
{expression for item in iterable}
words = ["hello", "HELLO", "Hello", "world", "WORLD"]
unique_lower = {word.lower() for word in words}
print(unique_lower)
Nested comprehensions¶
You can nest for clauses to work with multiple iterables. For example, creating all pairs from two lists:
colours = ["red", "blue"]
sizes = ["small", "large"]
combinations = [(colour, size) for colour in colours for size in sizes]
print(combinations)
Keep nested comprehensions simple. If the logic becomes hard to read, a regular loop is usually clearer.
When to use comprehensions versus loops¶
Comprehensions are best when:
- The logic is simple and fits comfortably on one or two lines
- You are creating a new collection from an existing one
- The transformation or filter is straightforward
Use a regular loop when:
- The logic involves multiple steps or side effects
- The comprehension would be difficult to read
- You need to handle exceptions or use
breakandcontinue
Generator expressions¶
If you replace the square brackets with parentheses, you get a generator expression. Generators produce items one at a time instead of building the entire collection in memory, which is useful for large datasets:
# List comprehension — builds the entire list in memory
total_list = sum([x ** 2 for x in range(1000)])
# Generator expression — computes values one at a time
total_gen = sum(x ** 2 for x in range(1000))
print(total_list == total_gen) # Same result, different memory usage
Exercise: word length dictionary¶
Given the following list of words:
words = ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
Using comprehensions:
- Create a dictionary mapping each word to its length, but only for words longer than three characters
- Create a set of all unique word lengths
- Create a list of words sorted by length (shortest first), with duplicates removed
# Write your code here
Solution¶
Here is one way to complete the exercise:
words = ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
# 1. Dictionary of words longer than three characters
long_words = {word: len(word) for word in words if len(word) > 3}
print(f"Long words: {long_words}")
# 2. Set of unique word lengths
lengths = {len(word) for word in words}
print(f"Unique lengths: {lengths}")
# 3. Sorted unique words by length
unique_words = list(dict.fromkeys(words)) # Remove duplicates, keep order
sorted_by_length = sorted(unique_words, key=len)
print(f"Sorted by length: {sorted_by_length}")
Summary¶
In this tutorial, you learned how to:
- Create lists with list comprehensions using
[expression for item in iterable] - Filter items with conditional comprehensions using
if - Build dictionaries with
{key: value for item in iterable} - Build sets with
{expression for item in iterable} - Use nested comprehensions for combinations
- Choose between comprehensions and regular loops
- Use generator expressions for memory efficiency
What is next¶
In the next tutorial, you will explore:
- Slicing and unpacking — advanced techniques for extracting and selecting data from sequences