Intermediate Python
34 min read
Advanced Comprehensions
Advanced Comprehensions
You already learned basic comprehensions.
Example:
numbers = [1, 2, 3, 4]
squares = [n * n for n in numbers]
Comprehensions can do more than simple lists.
You can add conditions, nested loops, sets, and dictionaries.
Why Comprehensions Matter
They help you:
- write shorter code
- transform data quickly
- filter values easily
- build collections cleanly
Review: Basic List Comprehension
numbers = [1, 2, 3, 4]
squares = [n * n for n in numbers]
print(squares)
Output
[1, 4, 9, 16]
Add Condition
numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
Output
[2, 4, 6]
If Else in Expression
numbers = [1, 2, 3, 4]
labels = ["Even" if n % 2 == 0 else "Odd" for n in numbers]
print(labels)
Output
['Odd', 'Even', 'Odd', 'Even']
Nested Loop Comprehension
pairs = [(x, y) for x in [1, 2] for y in ["A", "B"]]
print(pairs)
Output
[(1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]
Set Comprehension
numbers = [1, 1, 2, 2, 3]
unique = {n for n in numbers}
print(unique)
Output
{1, 2, 3}
Dictionary Comprehension
numbers = [1, 2, 3]
result = {n: n * n for n in numbers}
print(result)
Output
{1: 1, 2: 4, 3: 9}
Practical Example
names = ["tom", "maya", "liam"]
upper_names = [name.upper() for name in names]
print(upper_names)
Output
['TOM', 'MAYA', 'LIAM']
Code Along
Create a list of numbers 1 to 10.
Use a comprehension to create only odd numbers.
Mini Challenge
Use:
words = ["apple", "banana", "kiwi"]
Tasks:
-
Create a list of word lengths
-
Create a dictionary where:
- key = word
- value = length
Expected output:
[5, 6, 4]
{'apple': 5, 'banana': 6, 'kiwi': 4}
Real World Use Case
Developers use comprehensions for data cleaning, filtering, APIs, reports, and transformations.
Quiz
- Can comprehensions use conditions?
- What does a set comprehension create?
- What does a dictionary comprehension create?
- Why are comprehensions useful?
Assignment
Create a dictionary comprehension that maps numbers 1 to 5 to their cubes.
Summary
You learned how to use advanced comprehensions with conditions, nested loops, sets, and dictionaries.