Python Comprehensions
Learn how to create lists, sets, dictionaries, and generator expressions in a concise and powerful Pythonic way.
What You Will Learn
- Understand the idea behind comprehensions.
- Create lists using list comprehensions.
- Use conditions inside comprehensions.
- Create sets and dictionaries with comprehensions.
- Understand nested comprehensions.
- Use generator expressions for efficient iteration.
- Know when comprehensions improve code and when traditional loops are clearer.
What Are Comprehensions?
A comprehension is a concise way to create a new collection from an existing iterable.
Instead of writing several lines of a traditional
for loop, Python allows us to express the
same transformation in a compact form.
The most common type is the list comprehension.
numbers = [1, 2, 3, 4, 5]
squares = []
for number in numbers:
squares.append(number ** 2)
print(squares)
numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]
print(squares)
[1, 4, 9, 16, 25]
Why Use Comprehensions?
Comprehensions can make repetitive collection-building code shorter and easier to understand.
They are particularly useful when your transformation is simple and follows a clear pattern.
Convert every number into its square, select even numbers, clean simple text, or transform values.
If a comprehension becomes difficult to read, a normal loop may be the better choice.
List Comprehension Basics
A list comprehension creates a new list by processing items from an iterable.
numbers = [1, 2, 3, 4, 5]
doubles = [number * 2 for number in numbers]
print(doubles)
[2, 4, 6, 8, 10]
List Comprehension Syntax
The basic structure is:
[expression for item in iterable]
Think about the parts separately:
- expression — what you want to put into the new list.
- item — the current item.
- iterable — the collection being processed.
names = ["ali", "sara", "ahmed"]
upper_names = [name.upper() for name in names]
print(upper_names)
['ALI', 'SARA', 'AHMED']
Transforming Values
One of the most useful purposes of comprehensions is transforming every item in a collection.
prices = [100, 200, 300, 400]
discounted = [price * 0.9 for price in prices]
print(discounted)
[90.0, 180.0, 270.0, 360.0]
The expression is applied to every item.
Adding Conditions
A comprehension can include an if condition
to decide which items should be included.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [
number
for number in numbers
if number % 2 == 0
]
print(even_numbers)
[2, 4, 6]
Only values satisfying the condition are included.
Using if-else in Comprehensions
An if-else expression can transform every
item differently depending on a condition.
numbers = [1, 2, 3, 4, 5]
labels = [
"Even" if number % 2 == 0 else "Odd"
for number in numbers
]
print(labels)
['Odd', 'Even', 'Odd', 'Even', 'Odd']
A filtering if appears after the
for portion, while an
if-else expression appears before
the for.
Using range()
Comprehensions work very well with
range().
squares = [number ** 2 for number in range(1, 6)]
print(squares)
[1, 4, 9, 16, 25]
You can also generate a sequence of even numbers.
even_numbers = [
number
for number in range(2, 21, 2)
]
print(even_numbers)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Comprehensions with Strings
Strings are iterable, so you can process their characters using a comprehension.
word = "Python"
letters = [letter.upper() for letter in word]
print(letters)
['P', 'Y', 'T', 'H', 'O', 'N']
You can also filter characters.
word = "Programming"
vowels = [
letter
for letter in word.lower()
if letter in "aeiou"
]
print(vowels)
['o', 'a', 'i']
Nested Loops
Before learning nested comprehensions, understand what happens with nested loops.
numbers = []
for x in [1, 2, 3]:
for y in [10, 20]:
numbers.append((x, y))
print(numbers)
[(1, 10), (1, 20), (2, 10), (2, 20), (3, 10), (3, 20)]
The inner loop runs completely for each item of the outer loop.
Nested Comprehensions
Nested loops can sometimes be represented using a nested comprehension.
pairs = [
(x, y)
for x in [1, 2, 3]
for y in [10, 20]
]
print(pairs)
[(1, 10), (1, 20), (2, 10), (2, 20), (3, 10), (3, 20)]
They are powerful, but several nested levels can make your code harder to understand. A normal loop may be clearer.
Set Comprehensions
Set comprehensions use curly braces and create a set instead of a list.
numbers = [1, 2, 2, 3, 4, 4, 5]
squares = {
number ** 2
for number in numbers
}
print(squares)
{1, 4, 9, 16, 25}
Duplicate results are automatically removed because sets contain unique elements.
Dictionary Comprehensions
Dictionary comprehensions allow you to create dictionaries using a concise syntax.
numbers = [1, 2, 3, 4, 5]
squares = {
number: number ** 2
for number in numbers
}
print(squares)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The general pattern is:
{key_expression: value_expression for item in iterable}
Conditional Dictionary Comprehensions
You can filter dictionary entries using an
if condition.
numbers = [1, 2, 3, 4, 5, 6]
even_squares = {
number: number ** 2
for number in numbers
if number % 2 == 0
}
print(even_squares)
{2: 4, 4: 16, 6: 36}
Practical Example
marks = {
"Ali": 82,
"Sara": 91,
"Ahmed": 45,
"Hina": 76
}
passed = {
name: score
for name, score in marks.items()
if score >= 50
}
print(passed)
{'Ali': 82, 'Sara': 91, 'Hina': 76}
Generator Expressions
A generator expression looks similar to a list comprehension, but it uses parentheses instead of square brackets.
numbers = (number ** 2 for number in range(1, 6))
for number in numbers:
print(number)
1 4 9 16 25
A list comprehension creates the complete list immediately. A generator produces values as they are requested.
Generators can be much more memory-efficient when working with large sequences because they do not need to store every generated value at once.
Readability & Best Practices
Python encourages readable code. A comprehension should make simple logic easier to understand, not turn simple logic into a puzzle.
Readable
even_numbers = [
number
for number in numbers
if number % 2 == 0
]
Potentially Too Complex
result = [
x * y
for x in numbers
for y in other_numbers
if x % 2 == 0
if y > 10
]
The second example is valid Python, but if the logic becomes more complicated, a normal loop with descriptive variable names may be easier to maintain.
Prefer clarity over cleverness. Shorter code is not automatically better code.
Real-World Examples
Cleaning Product Names
products = [
" laptop ",
" PHONE ",
" tablet "
]
cleaned = [
product.strip().title()
for product in products
]
print(cleaned)
['Laptop', 'Phone', 'Tablet']
Filtering Prices
prices = [500, 1200, 800, 2500, 300]
expensive = [
price
for price in prices
if price >= 1000
]
print(expensive)
[1200, 2500]
Student Grades
marks = {
"Ali": 85,
"Sara": 92,
"Ahmed": 48,
"Hina": 76
}
grades = {
name: "Pass" if score >= 50 else "Fail"
for name, score in marks.items()
}
print(grades)
{'Ali': 'Pass', 'Sara': 'Pass', 'Ahmed': 'Fail', 'Hina': 'Pass'}
Common Comprehension Mistakes
Mistake 1 — Forgetting the Expression
# Incorrect
numbers = [for number in range(5)]
A comprehension needs an expression before the
for.
# Correct
numbers = [number for number in range(5)]
Mistake 2 — Confusing Filtering with if-else
A filtering condition comes after the iterable:
[number for number in numbers if number > 5]
An if-else expression comes before the
for:
["Pass" if mark >= 50 else "Fail" for mark in marks]
Mistake 3 — Making It Too Complicated
If you need several nested conditions, multiple function calls, or complicated calculations, consider using a normal loop.
Practice Exercises
Exercise 1 — Squares
Create a list containing the squares of numbers from 1 to 10 using a list comprehension.
Exercise 2 — Even Numbers
Create a list containing all even numbers from 1 to 50.
Exercise 3 — Word Lengths
Given a list of words, create a new list containing the length of every word.
Exercise 4 — Uppercase Names
Convert a list of lowercase names into uppercase names using a comprehension.
Exercise 5 — Filter Prices
Given a list of product prices, create a new list containing only prices greater than 1000.
Exercise 6 — Set Comprehension
Given a list containing duplicate numbers, create a set containing their squares.
Exercise 7 — Dictionary Comprehension
Create a dictionary where numbers from 1 to 5 are keys and their cubes are values.
Exercise 8 — Pass or Fail
Given a dictionary of student marks, create a new
dictionary containing "Pass" or
"Fail" for each student.
Mini Challenge — Student Performance Analyzer
Build a small program that analyzes student marks using dictionary comprehensions.
Start with this data:
students = {
"Ali": 82,
"Sara": 91,
"Ahmed": 45,
"Hina": 76,
"Usman": 38
}
Your program should:
- Create a dictionary of students who passed.
- Create a dictionary of students who failed.
- Create a dictionary containing each student's percentage.
- Display the results clearly.
students = {
"Ali": 82,
"Sara": 91,
"Ahmed": 45,
"Hina": 76,
"Usman": 38
}
passed = {
name: mark
for name, mark in students.items()
if mark >= 50
}
failed = {
name: mark
for name, mark in students.items()
if mark < 50
}
percentages = {
name: f"{mark}%"
for name, mark in students.items()
}
print("Passed:", passed)
print("Failed:", failed)
print("Percentages:", percentages)
Passed: {'Ali': 82, 'Sara': 91, 'Hina': 76}
Failed: {'Ahmed': 45, 'Usman': 38}
Percentages: {'Ali': '82%', 'Sara': '91%', 'Ahmed': '45%', 'Hina': '76%', 'Usman': '38%'}
Add grades such as A, B, C, D, and F using conditional expressions inside a dictionary comprehension.
Quick Knowledge Check
Test your understanding of Python comprehensions.
1. Which brackets are normally used for a list comprehension?
2. What does this create?
[x * 2 for x in numbers]
3. Where does a filtering if normally
appear?
4. Which syntax creates a set comprehension?
5. What makes a dictionary comprehension different?
6. What does a generator expression use?
7. What is an important reason to avoid overly complex comprehensions?
8. Which statement is true about generator expressions?
Lesson Summary
Comprehensions provide a powerful and Pythonic way to create and transform collections.
Use comprehensions when they make simple transformations concise and readable. When logic becomes complicated, choose clarity and use a traditional loop.
Ready to Continue?
You have learned how to use list, set, dictionary, and generator comprehensions to process data more efficiently and expressively.