What is List Comprehension?
A concise way to create lists. One line replaces 3-4 lines of loop code.
# Traditional loop
squares = []
for n in range(10):
squares.append(n ** 2)
# List comprehension โ same result
squares = [n ** 2 for n in range(10)]
Basic Syntax
[expression for item in iterable] # Examples [n * 2 for n in range(5)] # [0, 2, 4, 6, 8] [c.upper() for c in "hkdse"] # ['H', 'K', 'D', 'S', 'E'] [x for x in [1, 2, 3]] # [1, 2, 3]
With Condition
[expression for item in iterable if condition] # Even numbers only [n for n in range(20) if n % 2 == 0] # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # Pass scores scores = [45, 72, 85, 33, 91, 58] passes = [s for s in scores if s >= 50] # [72, 85, 91, 58]
With if/else Expression
# Grade each score scores = [45, 72, 85, 91] grades = ["A" if s >= 80 else "B" if s >= 60 else "F" for s in scores] # ['F', 'B', 'A', 'A']
Nested Comprehension
# Flatten 2D list grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat = [x for row in grid for x in row] # [1, 2, 3, 4, 5, 6, 7, 8, 9] # Create 2D list matrix = [[0 for _ in range(3)] for _ in range(3)] # [[0,0,0], [0,0,0], [0,0,0]]
Real Examples
# Extract names from tuples
students = [("Chan", 85), ("Lee", 72), ("Wong", 91)]
names = [s[0] for s in students]
# ["Chan", "Lee", "Wong"]
# Convert strings to numbers
lines = ["85", "72", "91"]
scores = [int(x) for x in lines]
# [85, 72, 91]
# Clean and uppercase
words = [" hello ", " world "]
clean = [w.strip().upper() for w in words]
# ["HELLO", "WORLD"]
# Filter + transform in one
scores = [85, 72, 91, 33, 45]
grades = [("A" if s >= 80 else "B") for s in scores if s >= 50]
# ["A", "B", "A"]
Dictionary Comprehension
# {key: value for item in iterable}
squares = {n: n**2 for n in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Swap keys and values
grades = {"Chan": "A", "Lee": "B"}
swapped = {v: k for k, v in grades.items()}
# {"A": "Chan", "B": "Lee"}
When NOT to Use Comprehension
- When the expression becomes too complex (readability matters)
- When you need side effects (use a loop)
- When the list would be huge (use generator expression)
HKDSE Consideration
List comprehension is NOT required for HKDSE, but using it shows maturity. Examiners recognise clean Pythonic code and may award bonus marks for elegance.
Practise in PyForm
Try rewriting your old loops as list comprehensions. You'll be amazed at how much code you can save.
Open PyForm โ