Comprehensions and Built-ins
Write concise solutions using list/dict/set comprehensions, map, filter, zip, enumerate, and sorted with key functions.
List Comprehensions: Concise Filtering
A list comprehension turns a for-loop-plus-append into one clean line: [expr for item in iterable if condition]. It is a little faster and signals Python fluency.
# Traditional loop
squares = []
for n in range(1, 6):
squares.append(n * n)
print(squares) # [1, 4, 9, 16, 25]
# List comprehension
squares = [n * n for n in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With filter
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]Nested Comprehensions for 2D Grids
Nested comprehensions build 2D grids — the standard way to set up a DP table. Avoid [[0]*C]*R, which shares one inner list across every row. The code shows the fix.
# WRONG: all rows are the same object!
bad = [[0] * 3] * 3
bad[0][0] = 9
print(bad) # [[9,0,0],[9,0,0],[9,0,0]] oops!
# CORRECT: each row is a separate list
good = [[0] * 3 for _ in range(3)]
good[0][0] = 9
print(good) # [[9,0,0],[0,0,0],[0,0,0]]All lessons in this course
- Lists, Tuples, and Slicing
- Dictionaries and Sets in Python
- Comprehensions and Built-ins
- Functions, Closures, and Lambda