Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Introduction to Comprehensions
List comprehensions are a concise way to create lists. They combine a for loop and an optional condition into a single line. This is a Pythonic feature you'll use everywhere.
List Comprehensions
# Without comprehension (traditional)
squares = []
for i in range(1, 6):
squares.append(i ** 2)
print(squares) # [1, 4, 9, 16, 25]
# With list comprehension - one line!
squares = [i ** 2 for i in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# Comprehension with condition
evens = [i for i in range(20) if i % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# String comprehension
name = "Hello World"
upper = [c.upper() for c in name if c != " "]
print(upper) # ['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']
# Comprehension with expression
words = ["hello", "world", "python"]
capitalized = [w.capitalize() for w in words]
print(capitalized) # ['Hello', 'World', 'Python']
# if-else in comprehension
nums = [1, -2, 3, -4, 5]
signs = ["+" if n > 0 else "-" for n in nums]
print(signs) # ['+', '-', '+', '-', '+']Tip
Tip
List comprehensions are 10-30% faster than for loops because they're optimized at the bytecode level. Use them for simple transformations.
List comp for most cases. Generator for large data (lazy). Dict comp for transforming dicts. Readable > clever.
Common Mistake
Warning
Don't nest comprehensions more than 2 levels deep. Deeper nesting becomes unreadable - use regular loops.
Practice Task
Note
(1) Create squares of 1-10. (2) Filter words longer than 3 characters. (3) Convert names to uppercase. (4) Create (number, square) tuples.