Python List Comprehensions
List comprehensions provide a concise, readable way to create lists. They combine a for loop and an optional condition into a single line, and are considered one of Python's most powerful features.
Basic Syntax
python
# Syntax: [expression for item in iterable]
# Traditional loop
squares = []
for x in range(10):
squares.append(x ** 2)
# List comprehension (same result)
squares = [x ** 2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]With Conditions
Filtering (if)
python
# [expression for item in iterable if condition]
# Even numbers only
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Positive numbers
numbers = [-3, -1, 0, 2, 5, -4, 8]
positive = [n for n in numbers if n > 0]
print(positive) # [2, 5, 8]
# Filter strings
words = ["hello", "", "world", "", "python"]
non_empty = [w for w in words if w]
print(non_empty) # ['hello', 'world', 'python']
# Multiple conditions
nums = range(100)
result = [x for x in nums if x % 2 == 0 if x % 3 == 0]
print(result) # [0, 6, 12, 18, 24, 30, ...] (divisible by both 2 and 3)Conditional Expression (if-else)
python
# [expr_if_true if condition else expr_if_false for item in iterable]
labels = ["even" if x % 2 == 0 else "odd" for x in range(6)]
print(labels) # ['even', 'odd', 'even', 'odd', 'even', 'odd']
# Absolute values
numbers = [-3, -1, 0, 2, -5, 8]
absolute = [x if x >= 0 else -x for x in numbers]
print(absolute) # [3, 1, 0, 2, 5, 8]
# Grade classification
scores = [92, 45, 78, 88, 35, 67]
results = ["pass" if s >= 50 else "fail" for s in scores]
print(results) # ['pass', 'fail', 'pass', 'pass', 'fail', 'pass']Nested Comprehensions
Nested Loops
python
# Flatten a 2D list
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]
# Equivalent nested loop:
# for row in matrix:
# for num in row:
# flat.append(num)
# All combinations
colors = ["red", "blue"]
sizes = ["S", "M", "L"]
combos = [(c, s) for c in colors for s in sizes]
print(combos)
# [('red', 'S'), ('red', 'M'), ('red', 'L'),
# ('blue', 'S'), ('blue', 'M'), ('blue', 'L')]Creating 2D Lists
python
# 3x3 matrix of zeros
matrix = [[0 for _ in range(3)] for _ in range(3)]
print(matrix) # [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
# Identity matrix
identity = [[1 if i == j else 0 for j in range(4)] for i in range(4)]
for row in identity:
print(row)
# [1, 0, 0, 0]
# [0, 1, 0, 0]
# [0, 0, 1, 0]
# [0, 0, 0, 1]
# Multiplication table
table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
for row in table:
print(row)Dictionary Comprehensions
python
# {key_expr: value_expr for item in iterable}
# Squares dictionary
squares = {x: x**2 for x in range(6)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# From two lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
people = {name: age for name, age in zip(names, ages)}
print(people) # {'Alice': 25, 'Bob': 30, 'Charlie': 35}
# Filter and transform
prices = {"apple": 1.20, "banana": 0.50, "cherry": 2.00, "date": 3.50}
affordable = {k: v for k, v in prices.items() if v < 2.0}
print(affordable) # {'apple': 1.20, 'banana': 0.50}
# Invert a dictionary
inverted = {v: k for k, v in prices.items()}
print(inverted)
# Word lengths
sentence = "python list comprehensions are awesome"
lengths = {word: len(word) for word in sentence.split()}
print(lengths)
# {'python': 6, 'list': 4, 'comprehensions': 14, 'are': 3, 'awesome': 7}Set Comprehensions
python
# {expression for item in iterable}
# Unique squares
squares = {x**2 for x in range(-5, 6)}
print(squares) # {0, 1, 4, 9, 16, 25}
# Unique first letters
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
first_letters = {w[0] for w in words}
print(first_letters) # {'a', 'b', 'c'}Generator Expressions
Like list comprehensions but lazy β they compute values on demand:
python
# Generator expression (round brackets)
gen = (x**2 for x in range(10))
print(type(gen)) # <class 'generator'>
# Use in functions that accept iterables
total = sum(x**2 for x in range(10))
print(total) # 285
# Memory efficient for large datasets
# List: stores all values in memory
big_list = [x**2 for x in range(1_000_000)] # Uses lots of memory
# Generator: computes on demand
big_gen = (x**2 for x in range(1_000_000)) # Uses minimal memory
# Check if any/all
has_negative = any(x < 0 for x in [1, -2, 3])
print(has_negative) # True
all_positive = all(x > 0 for x in [1, 2, 3])
print(all_positive) # True
# Find max
longest = max(["apple", "banana", "cherry"], key=lambda x: len(x))
print(longest) # bananaPractical Examples
Data Processing Pipeline
python
# Process a list of student records
students = [
{"name": "Alice", "scores": [92, 88, 95]},
{"name": "Bob", "scores": [78, 82, 75]},
{"name": "Charlie", "scores": [95, 98, 92]},
{"name": "Diana", "scores": [65, 70, 68]},
]
# Calculate averages
averages = {
s["name"]: sum(s["scores"]) / len(s["scores"])
for s in students
}
print(averages)
# {'Alice': 91.67, 'Bob': 78.33, 'Charlie': 95.0, 'Diana': 67.67}
# Honor roll (average >= 85)
honor_roll = [
s["name"] for s in students
if sum(s["scores"]) / len(s["scores"]) >= 85
]
print(f"Honor Roll: {honor_roll}")
# Honor Roll: ['Alice', 'Charlie']Text Processing
python
# Clean and process text
raw_data = [" Alice ", "BOB", " charlie", "", " DIANA ", " "]
# Clean: strip, title case, filter empty
cleaned = [name.strip().title() for name in raw_data if name.strip()]
print(cleaned) # ['Alice', 'Bob', 'Charlie', 'Diana']
# Extract emails from text
lines = [
"Contact: alice@example.com",
"No email here",
"Send to: bob@test.org",
"Info at charlie@demo.com"
]
emails = [
word for line in lines
for word in line.split()
if "@" in word
]
print(emails) # ['alice@example.com', 'bob@test.org', 'charlie@demo.com']When NOT to Use Comprehensions
python
# DON'T: complex logic with side effects
# BAD - hard to read
result = [print(x) or x**2 for x in range(5) if x % 2 == 0]
# GOOD - use a regular loop
for x in range(5):
if x % 2 == 0:
print(x)
# DON'T: extremely long comprehensions
# BAD
r = [transform(x) for x in data if validate(x) and check_permission(x) and not is_deleted(x)]
# GOOD - break it down
valid = [x for x in data if validate(x)]
permitted = [x for x in valid if check_permission(x)]
active = [x for x in permitted if not is_deleted(x)]
result = [transform(x) for x in active]Summary
- List comprehensions
[expr for x in iterable]create lists concisely - Add filtering with
if:[x for x in items if condition] - Add conditional value with
if-else:[a if cond else b for x in items] - Nested comprehensions handle multi-level iteration
- Dictionary comprehensions
{k: v for ...}create dicts - Set comprehensions
{expr for ...}create sets - Generator expressions
(expr for ...)are memory-efficient for large data - Keep comprehensions readable β use regular loops for complex logic
Next, we'll learn about Python classes and object-oriented programming.