- Basic syntax — how list comprehension works
- Conditional filtering — using if to filter elements
- if-else in comprehension — conditional expressions
- Nested comprehension — working with nested loops
- Multiple conditions — combining filters
- Performance — when and why to use comprehension
- Common mistakes — and how to avoid them
Introduction to List Comprehension
List comprehension is a concise and powerful Python feature that allows you to create new lists by applying an expression to each element of an existing iterable. It combines the process of iteration and transformation into a single, readable line of code.
List comprehensions are often more readable and performant than traditional for loops for list creation. They follow a natural syntax that closely resembles how you would describe the operation in plain English.
The basic structure of a list comprehension is:
new_list = [expression for item in iterable if condition]
Where:
- expression — the operation to perform on each element
- item — the variable representing each element
- iterable — the source collection (list, range, etc.)
- if condition — optional filter (only include items that satisfy the condition)
💡 Key concept: List comprehension is a syntactic sugar for a for loop with an append operation. It is not always the best choice — use it for simple transformations and filters, but avoid it when readability would suffer.
Basic Syntax
Transforming Elements
The simplest form of list comprehension applies an expression to each element in the iterable and creates a new list with the results.
# Basic list comprehension
numbers = [1, 2, 3, 4, 5]
# Square each number
squares = [num ** 2 for num in numbers]
print(squares) # [1, 4, 9, 16, 25]
# Convert to strings
str_numbers = [str(num) for num in numbers]
print(str_numbers) # ['1', '2', '3', '4', '5']
# Apply a function
def double(x):
return x * 2
doubled = [double(num) for num in numbers]
print(doubled) # [2, 4, 6, 8, 10]
# Working with strings
words = ["apple", "banana", "cherry"]
uppercase = [word.upper() for word in words]
print(uppercase) # ['APPLE', 'BANANA', 'CHERRY']
# Get lengths
lengths = [len(word) for word in words]
print(lengths) # [5, 6, 6]
Characteristics:
- Creates a new list — original list remains unchanged
- Syntax:
[expression for item in iterable] - Can use any expression including function calls
- Works with any iterable (lists, tuples, ranges, etc.)
- Often faster than equivalent for loop
Quick Check: Does list comprehension modify the original list? (Answer: No, it creates a new list)
With Conditional Filtering
Filtering Elements with if
The if clause in a list comprehension allows you to filter elements — only items that satisfy the condition are included in the new list.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Only even numbers
evens = [num for num in numbers if num % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Only numbers greater than 5
greater_than_5 = [num for num in numbers if num > 5]
print(greater_than_5) # [6, 7, 8, 9, 10]
# With strings - words with length > 5
words = ["apple", "banana", "cherry", "date", "elderberry"]
long_words = [word for word in words if len(word) > 5]
print(long_words) # ['banana', 'cherry', 'elderberry']
# Words starting with a specific letter
a_words = [word for word in words if word.startswith('a')]
print(a_words) # ['apple']
# Filtering and transforming together
squares_of_evens = [num ** 2 for num in numbers if num % 2 == 0]
print(squares_of_evens) # [4, 16, 36, 64, 100]
Characteristics:
- Syntax:
[expression for item in iterable if condition] - Only items that satisfy the condition are included
- Can be combined with transformation in the same line
- Equivalent to:
for item in iterable: if condition: append(expression)
Quick Check: What does the if clause do in list comprehension? (Answer: It filters elements — only those that satisfy the condition are included)
Using if-else in Comprehension
Conditional Expressions
The if-else construct can be used within the expression part of a list comprehension to apply different transformations based on a condition.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Replace even numbers with "even", odd with "odd" labels = ["even" if num % 2 == 0 else "odd" for num in numbers] print(labels) # ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even'] # Mark numbers greater than 5 as "high", others as "low" categories = ["high" if num > 5 else "low" for num in numbers] print(categories) # ['low', 'low', 'low', 'low', 'low', 'high', 'high', 'high', 'high', 'high'] # Square even numbers, leave odd numbers unchanged processed = [num ** 2 if num % 2 == 0 else num for num in numbers] print(processed) # [1, 4, 3, 16, 5, 36, 7, 64, 9, 100] # With strings - convert to uppercase if length > 3, else lowercase words = ["apple", "banana", "cat", "dog", "elderberry"] modified = [word.upper() if len(word) > 3 else word.lower() for word in words] print(modified) # ['APPLE', 'BANANA', 'cat', 'dog', 'ELDERBERRY']
Important distinction:
- if at the end — filters items:
[x for x in list if condition] - if-else in expression — transforms items:
[x if condition else y for x in list] - Both can be used in the same comprehension
# Filter AND transform result = [num ** 2 if num % 2 == 0 else num for num in numbers if num > 3] # First filter: num > 3, then transform: square if even, keep if odd
Quick Check: What is the difference between if at the end and if-else in expression? (Answer: if at the end filters; if-else in expression transforms)
Nested List Comprehension
Working with Nested Loops
List comprehension can include nested loops, similar to nested for loops. This is useful for flattening lists or working with matrices.
# Flatten a matrix (list of lists) matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flattened = [num for row in matrix for num in row] print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9] # Equivalent nested for loop: # flattened = [] # for row in matrix: # for num in row: # flattened.append(num) # Nested comprehension with filtering matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] even_numbers = [num for row in matrix for num in row if num % 2 == 0] print(even_numbers) # [2, 4, 6, 8] # Creating a multiplication table table = [[i * j for j in range(1, 6)] for i in range(1, 6)] print(table) # [[1, 2, 3, 4, 5], # [2, 4, 6, 8, 10], # [3, 6, 9, 12, 15], # [4, 8, 12, 16, 20], # [5, 10, 15, 20, 25]] # Transpose a matrix matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] transposed = [[row[i] for row in matrix] for i in range(3)] print(transposed) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Characteristics:
- Loop order follows the same order as nested for loops
- Can have multiple levels of nesting
- Useful for flattening and matrix operations
- Readability decreases with too many nested levels
Quick Check: What is the order of loops in a nested list comprehension? (Answer: The order matches nested for loops — outer loop first, then inner loop)
Multiple Conditions
Combining Filters
List comprehension supports multiple conditions using multiple if clauses or logical operators.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Multiple if conditions result = [num for num in numbers if num > 3 if num < 8] print(result) # [4, 5, 6, 7] # Using logical operators (and, or) result = [num for num in numbers if num > 3 and num < 8] print(result) # [4, 5, 6, 7] # Numbers that are even OR greater than 7 result = [num for num in numbers if num % 2 == 0 or num > 7] print(result) # [2, 4, 6, 8, 9, 10] # With strings - words with length > 3 AND contain 'a' words = ["apple", "banana", "cat", "dog", "grape", "kiwi"] result = [word for word in words if len(word) > 3 and 'a' in word] print(result) # ['apple', 'banana', 'grape']
Guidelines:
- Multiple
ifclauses act as AND conditions - Use
and,orfor more complex logic - Multiple if clauses are less common than using and/or
- Keep conditions simple for readability
Performance Considerations
When to Use List Comprehension
List comprehension is generally faster than a for loop because it is implemented in C and optimized for list creation. However, readability should be the primary consideration.
import time
# Using for loop
numbers = range(1, 1000000)
start = time.time()
squares_loop = []
for num in numbers:
squares_loop.append(num ** 2)
print(f"Loop time: {time.time() - start:.4f}s")
# Using list comprehension
numbers = range(1, 1000000)
start = time.time()
squares_comp = [num ** 2 for num in numbers]
print(f"Comprehension time: {time.time() - start:.4f}s")
# Output (approximate):
# Loop time: 0.1234s
# Comprehension time: 0.0789s
# When NOT to use list comprehension:
# 1. Complex logic
# 2. Side effects (e.g., printing)
# 3. Multiple operations
# 4. Very large datasets (memory considerations)
Performance summary:
- Faster: List comprehension is usually faster than for loops
- Memory: Creates a complete list in memory
- Use when: Simple transformation or filtering
- Avoid when: Complex logic, side effects, or very large datasets
- For very large data: Consider generator expressions:
(x ** 2 for x in numbers)
Quick Check: Is list comprehension always the best choice? (Answer: No — avoid it for complex logic, side effects, or very large datasets)
Common Mistakes
Pitfalls and Solutions
Confusing Filter and Transformation
# Incorrect — trying to use if-else as a filter numbers = [1, 2, 3, 4, 5] # This will raise an error because if-else must be in the expression # result = [num if num % 2 == 0 for num in numbers] # SyntaxError # Correct — if-else in expression, if at end for filtering result = [num for num in numbers if num % 2 == 0] # Filter result = ["even" if num % 2 == 0 else "odd" for num in numbers] # Transform
Variable Shadowing
# Incorrect — overwrites existing variable numbers = [1, 2, 3, 4, 5] num = 10 # Original variable squares = [num ** 2 for num in numbers] # num is overwritten print(num) # 5 (not 10!) # Correct — use different variable names in comprehension squares = [n ** 2 for n in numbers]
Overly Complex Comprehensions
# Bad — too complex, hard to read
result = [x ** 2 if x % 2 == 0 else x ** 3 if x % 3 == 0 else x for x in range(1, 20)]
# Better — use a regular loop for complex logic
result = []
for x in range(1, 20):
if x % 2 == 0:
result.append(x ** 2)
elif x % 3 == 0:
result.append(x ** 3)
else:
result.append(x)
Using Comprehension for Side Effects
# Incorrect — using comprehension for side effects
numbers = [1, 2, 3, 4, 5]
# Don't do this: [print(num) for num in numbers] # Prints but creates an unnecessary list
# Correct — use a for loop for side effects
for num in numbers:
print(num)
Quick Check: When should you NOT use list comprehension? (Answer: When the logic is complex, for side effects, or when readability suffers)
Interactive Editor
Experiment with list comprehension in the interactive editor below. Modify the code and observe the results in real time.
LIST COMPREHENSION PRACTICE
========================================
Numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Words: ['apple', 'banana', 'cherry', 'date', 'elderberry']
1. BASIC TRANSFORMATION
Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
2. FILTERING
Even numbers: [2, 4, 6, 8, 10]
3. IF-ELSE IN EXPRESSION
Labels: ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']
4. NESTED COMPREHENSION
Flattened matrix: [1, 2, 3, 4, 5, 6, 7, 8, 9]
5. WORKING WITH STRINGS
Long words uppercase: ['BANANA', 'CHERRY', 'ELDERBERRY']
6. MULTIPLE CONDITIONS
Numbers between 3 and 8: [4, 5, 6, 7]
7. IF-ELSE WITH STRINGS
Modified words: ['apple', 'BANANA', 'CHERRY', 'date', 'ELDERBERRY']
List comprehension practice complete!
Certificate of Completion
You have completed the Python List Comprehension tutorial. You now understand basic syntax, conditional filtering, if-else in comprehension, nested comprehension, and performance considerations.
Quiz
Test your understanding of list comprehension:
Frequently Asked Questions
What is list comprehension in Python?
What is the difference between if at the end and if-else in comprehension?
[x for x in list if condition]. if-else in expression transforms elements: [x if condition else y for x in list]. The former filters; the latter transforms.
Is list comprehension faster than a for loop?
Can I have multiple if conditions in list comprehension?
and/or operators or multiple if clauses. For example: [x for x in list if x > 0 and x < 10].
Does list comprehension modify the original list?
When should I NOT use list comprehension?
Next Steps
After mastering list comprehension, consider exploring these related topics:
List Functions
Essential methods for list manipulation: append, pop, sort, and more.
Learn More →Dictionary Comprehension
Create dictionaries concisely using comprehension syntax.
Learn More →Set Comprehension
Create sets using comprehension syntax.
Learn More →