Learning

Comprehensions Mastery

Comprehensions Mastery

List Comprehensions

python
# Basic squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # With condition evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # With if-else (different from filter!) labels = ['even' if x % 2 == 0 else 'odd' for x in range(5)] # ['even', 'odd', 'even', 'odd', 'even'] # String processing words = ['hello', 'WORLD', 'Python'] cleaned = [w.lower().strip() for w in words] # ['hello', 'world', 'python']

Dict Comprehensions

python
# From two lists names = ['alice', 'bob', 'charlie'] scores = [95, 87, 92] grades = {name: score for name, score in zip(names, scores)} # {'alice': 95, 'bob': 87, 'charlie': 92} # Transform keys/values original = {'a': 1, 'b': 2, 'c': 3} upper = {k.upper(): v * 10 for k, v in original.items()} # {'A': 10, 'B': 20, 'C': 30} # Filter dict filtered = {k: v for k, v in original.items() if v > 1} # {'b': 2, 'c': 3}

Set Comprehensions

python
# Remove duplicates automatically nums = [1, 2, 2, 3, 3, 3, 4] unique_squares = {x**2 for x in nums} # {1, 4, 9, 16} # Find unique lengths words = ['hi', 'hey', 'yo', 'hello', 'bye'] lengths = {len(w) for w in words} # {2, 3, 5}

Nested Comprehensions

python
# Flatten a matrix matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat = [num for row in matrix for num in row] # [1, 2, 3, 4, 5, 6, 7, 8, 9] # Transpose a matrix transposed = [[row[i] for row in matrix] for i in range(3)] # [[1, 4, 7], [2, 5, 8], [3, 6, 9]] # Cartesian product pairs = [(x, y) for x in range(3) for y in range(3) if x != y] # [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)]

Walrus in Comprehensions

python
import re text = 'foo123bar456baz789' # Without walrus — calls findall twice # results = [m for m in re.findall(r'\d+', text) if int(m) > 200] # With walrus — compute once results = [int(m) for m in re.findall(r'\d+', text) if (n := int(m)) > 200] # [456, 789]
Key Rules
  • •List comprehension: [expr for item in iterable if condition] — condition filters, if-else transforms
  • •Dict comprehension: {key_expr: val_expr for item in iterable} — need both key and value expressions
  • •Set comprehension: {expr for item in iterable} — auto-deduplicates like a set
  • •Nested comprehensions read LEFT to RIGHT as nested loops: [x for row in matrix for x in row]
  • •There is NO tuple comprehension — (x for x in ...) creates a GENERATOR, not a tuple
  • •Keep comprehensions simple — if they need more than 2 lines, use a regular loop for readability
Your Task

Given a list of sentences, use a list comprehension to flatten all words (split by space). Use a dict comprehension to create a word frequency map from those words (lowercase). Use a set comprehension to find all unique word lengths. Use a nested comprehension to create a multiplication table (3x3). Use a walrus operator in a comprehension to filter strings that are longer than 4 characters after stripping whitespace.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should flatten words with nested list comprehension
Should create dict comprehension for frequency
Should use set comprehension for lengths
Should create nested comprehension for table
Should use walrus operator in comprehension
Should use .strip() in walrus comprehension