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! 🚀
List Comprehensions
List comprehensions are a concise Pythonic way to create lists from existing iterables. Syntax: [expression for item in iterable if condition].
Comprehensions
# Basic comprehension
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition (filter)
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# With transformation
words = ["hello", "world", "python"]
upper = [w.upper() for w in words]
print(upper) # ['HELLO', 'WORLD', 'PYTHON']
# if-else in expression
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
print(labels) # ['even', 'odd', 'even', 'odd', 'even']
# Nested comprehension (2D → 1D)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Practical: filter and transform
names = [" alice ", "BOB", " charlie"]
cleaned = [name.strip().title() for name in names]
print(cleaned) # ['Alice', 'Bob', 'Charlie']Tip
Tip
Use comprehensions for simple transforms and filters. For complex logic with multiple steps, use a regular for loop.
List comp for most cases. Generator for large data (lazy). Dict comp for transforming dicts. Readable > clever.
Common Mistake
Warning
if-else goes BEFORE 'for' in comprehensions. [x if x>0 else 0 for x in nums]. But filter goes AFTER: [x for x in nums if x>0].
Practice Task
Note
(1) Create squares of even numbers 0-20. (2) Flatten a 2D list. (3) Strip and capitalize a list of names. (4) Create (n, n²) tuples.