Topic 5 of 64
List Comprehensions
Overview
List comprehensions provide a concise, Pythonic way to create lists using a single expression. They are more readable and often faster than equivalent for loops — a staple of professional Python code.
Syntax
python
# Basic
squares = [x**2 for x in range(10)]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# Nested
matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
# Dict comprehension
word_lengths = {word: len(word) for word in ["Python", "Java", "Go"]}
# Set comprehension
unique_domains = {email.split("@")[1] for email in emails}
# Generator expression (lazy, memory efficient)
total = sum(x**2 for x in range(1_000_000)) # no list created!Common Pitfalls
- Deeply nested comprehensions (more than 2 levels) are hard to read — use regular loops instead.
- Use generator expressions (parentheses, not brackets) for large datasets to avoid creating huge lists in memory.
- Interview tip: dict comprehensions overwrite duplicate keys — the last value for a key wins.
Real-World Example
Processing an e-commerce dataset with comprehensions:
example
python
orders = [
{"id": 1, "product": "Laptop", "price": 45000, "qty": 1, "status": "delivered"},
{"id": 2, "product": "Phone", "price": 18000, "qty": 2, "status": "pending"},
{"id": 3, "product": "Tablet", "price": 22000, "qty": 1, "status": "delivered"},
{"id": 4, "product": "Watch", "price": 8000, "qty": 3, "status": "cancelled"},
]
# Revenue from delivered orders
revenue = sum(o["price"] * o["qty"] for o in orders if o["status"] == "delivered")
print(f"Revenue: ₹{revenue:,}") # ₹67,000
# Product name → price map (only delivered)
price_map = {
o["product"]: o["price"]
for o in orders
if o["status"] == "delivered"
}
# Flat list from nested data
all_tags = [tag for product in catalog for tag in product.get("tags", [])]