02. Comprehensions Revisited
Comprehensions are a concise way to create new lists, sets, and dictionaries in Python. They are more Pythonic than using loops for building collections, and often faster as well.
Why Comprehensions?
- Conciseness: Replace multiple lines of loops with one clear expression.
- Readability: Easier to understand intent at a glance.
- Performance: Comprehensions are implemented in C under the hood, often faster than explicit loops.
List Comprehensions
General form:
[expression for item in iterable if condition]
Example:
numbers = [1, 2, 3, 4, 5, 6]
squares = [n*n for n in numbers if n % 2 == 0]
print(squares) # [4, 16, 36]
Equivalent loop:
squares = []
for n in numbers:
if n % 2 == 0:
squares.append(n*n)
Nested List Comprehensions
You can nest comprehensions for multiple loops:
pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs)
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Set Comprehensions
Set comprehensions look like list comprehensions but use curly braces:
unique_squares = {n*n for n in numbers}
print(unique_squares)
Dictionary Comprehensions
General form:
{key_expr: value_expr for item in iterable if condition}
Example:
fruits = ["apple", "banana", "cherry"]
fruit_lengths = {fruit: len(fruit) for fruit in fruits}
print(fruit_lengths)
# {'apple': 5, 'banana': 6, 'cherry': 6}
Conditional Expressions in Comprehensions
You can use if...else directly inside expressions:
result = ["even" if n % 2 == 0 else "odd" for n in range(5)]
print(result) # ['even', 'odd', 'even', 'odd', 'even']
Practice Challenge
Rewrite this loop as a comprehension:
words = ["python", "is", "fun"]
uppercase_words = []
for word in words:
if len(word) > 2:
uppercase_words.append(word.upper())
print(uppercase_words)
👉 Hint: Use a list comprehension with a condition.
Wrap-Up
- Use list, set, and dictionary comprehensions for concise, readable code.
- Avoid deeply nested comprehensions; if they get too complex, use loops instead.
- Remember: readability counts, so choose clarity over cleverness.