List Comprehensions
Create lists efficiently using comprehensions in one line
List Comprehensions
What is a List Comprehension?
Think of list comprehension as a shortcut for creating lists. Instead of writing a loop that takes 3-4 lines, you write one line that does the same thing.
List comprehension is a clean, readable way to create new lists from existing lists or ranges.
Why use list comprehensions?
- Write less code (one line instead of multiple)
- Easier to read once you learn the pattern
- Runs faster than traditional loops
- Very common in Python code
Basic Pattern
The basic format looks like this:
new_list = [expression for item in sequence]Let's see a real example:
Old Way With Loop
numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
squares.append(num * num)
print(squares)Result: [1, 4, 9, 16, 25]
New Way With Comprehension
numbers = [1, 2, 3, 4, 5]
squares = [num * num for num in numbers]
print(squares)Result: [1, 4, 9, 16, 25]
Same result, much shorter!
How to read it: "Create a list where each item is num times num, for each num in numbers"
Simple Examples
Creating Doubled Numbers
numbers = [1, 2, 3, 4]
doubled = [n * 2 for n in numbers]
print(doubled)Result: [2, 4, 6, 8]
Converting to Uppercase
words = ["hello", "world", "python"]
upper = [word.upper() for word in words]
print(upper)Result: ['HELLO', 'WORLD', 'PYTHON']
Getting String Lengths
words = ["hi", "hello", "hey"]
lengths = [len(word) for word in words]
print(lengths)Result: [2, 5, 3]
Using Range
You can create lists from ranges without needing an existing list.
squares = [x * x for x in range(5)]
print(squares)Result: [0, 1, 4, 9, 16]
What happens: Creates squares for numbers 0 through 4.
evens = [x for x in range(10) if x % 2 == 0]
print(evens)Result: [0, 2, 4, 6, 8]
Adding Conditions
You can filter items using "if" at the end.
Basic Filtering
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
evens = [n for n in numbers if n % 2 == 0]
print(evens)Result: [2, 4, 6, 8]
How to read it: "Create a list with each n, for each n in numbers, but only if n is even"
Filtering Strings
words = ["apple", "banana", "kiwi", "orange"]
short = [w for w in words if len(w) <= 5]
print(short)Result: ['apple', 'kiwi']
What this does: Only includes words with 5 or fewer letters.
Filtering and Transforming
You can filter and change items at the same time.
numbers = [1, 2, 3, 4, 5, 6]
even_squares = [n * n for n in numbers if n % 2 == 0]
print(even_squares)Result: [4, 16, 36]
What happens: Takes only even numbers (2, 4, 6) and squares them.
If-Else in Comprehensions
When you want to do one thing if condition is true and another if false, put the if-else before the for.
numbers = [1, 2, 3, 4, 5]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)Result: ['odd', 'even', 'odd', 'even', 'odd']
Pattern: [value_if_true if condition else value_if_false for item in sequence]
Another example:
scores = [85, 92, 78, 95, 88]
results = ["Pass" if score >= 80 else "Fail" for score in scores]
print(results)Result: ['Pass', 'Pass', 'Fail', 'Pass', 'Pass']
Nested Comprehensions
You can use comprehensions inside comprehensions for nested loops.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]
How to read it: "For each row in matrix, for each num in that row, add num to the list"
This is the same as:
flat = []
for row in matrix:
for num in row:
flat.append(num)Working With Strings
Split and Process
sentence = "hello world python"
lengths = [len(word) for word in sentence.split()]
print(lengths)Result: [5, 5, 6]
What this does: Splits sentence into words, then gets length of each word.
Filter Characters
text = "Hello123World"
letters = [char for char in text if char.isalpha()]
print(letters)Result: ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
Joins them back:
result = "".join(letters)
print(result)Result: HelloWorld
Practice Example
The scenario: You're processing student test scores to analyze performance.
scores = [45, 67, 89, 92, 78, 55, 88, 73, 95, 62]
passing = [s for s in scores if s >= 70]
print("Passing scores:", passing)
failing = [s for s in scores if s < 70]
print("Failing scores:", failing)
adjusted = [s + 5 for s in scores]
print("After curve:", adjusted)
grades = ["A" if s >= 90 else "B" if s >= 80 else "C" if s >= 70 else "F" for s in scores]
print("Grades:", grades)
high_scores = [s for s in scores if s >= 80]
count = len(high_scores)
print("High scores count:", count)
doubled = [s * 2 for s in scores if s >= 80]
print("Doubled high scores:", doubled)What this program does:
- Filters passing scores (70 or above)
- Filters failing scores (below 70)
- Adds 5 points to all scores (grade curve)
- Assigns letter grades based on score ranges
- Counts how many high scores (80+)
- Doubles only the high scores
Key Points to Remember
List comprehension format is [expression for item in sequence]. This creates a new list by applying expression to each item.
Add "if condition" at the end to filter items. Only items that meet the condition are included.
For if-else logic, put it before the "for": [value_if_true if condition else value_if_false for item in sequence].
Comprehensions are faster and more readable than traditional loops for simple operations.
You can nest comprehensions for nested loops, but don't make them too complex or they become hard to read.
Common Mistakes
Mistake 1: Wrong if-else placement
nums = [1, 2, 3, 4]
result = [n * 2 for n in nums if n > 2 else n] # Wrong!
result = [n * 2 if n > 2 else n for n in nums] # Correct!Mistake 2: Too complex comprehension
result = [x * y if x > y else y * 2 if y > 5 else x + y for x in range(10) for y in range(10) if x != y]This is hard to read. Use a regular loop instead.
Mistake 3: Forgetting square brackets
squares = (x * x for x in range(5)) # This creates generator, not list
squares = [x * x for x in range(5)] # Correct!What's Next?
You now know list comprehensions. Next, you'll learn about dictionary and set comprehensions, which work similarly but create dictionaries and sets instead of lists.