List Comprehensions in Python: Write Cleaner Code
Master Python list comprehensions to write more readable and efficient code. Learn syntax, examples, and when to use them over traditional loops.
Moshiour Rahman
Advertisement
What Are List Comprehensions?
List comprehensions provide a concise way to create lists in Python. They allow you to transform and filter data in a single, readable line of code - almost like writing plain English.
Basic Syntax
# Traditional for loop
result = []
for item in iterable:
result.append(expression)
# List comprehension equivalent
result = [expression for item in iterable]
Simple Examples
Squaring Numbers
Traditional approach with map and lambda:
numbers = [10, 45, 34, 89, 34, 23, 6]
square_numbers = list(map(lambda num: num**2, numbers))
List comprehension (much cleaner!):
numbers = [10, 45, 34, 89, 34, 23, 6]
square_numbers = [num**2 for num in numbers]
# Output: [100, 2025, 1156, 7921, 1156, 529, 36]
Creating a List of Strings
# Create greetings for names
names = ['Alice', 'Bob', 'Charlie']
greetings = [f"Hello, {name}!" for name in names]
# Output: ['Hello, Alice!', 'Hello, Bob!', 'Hello, Charlie!']
List Comprehensions with Conditions
Add an if clause to filter items:
[expression for item in iterable if condition]
Example: Finding Vowels
Traditional for loop:
chars = ['t', 'e', 'c', 'h', 'y', 'o', 'w', 'l', 's']
vowels = ['a', 'e', 'i', 'o', 'u']
only_vowels = []
for char in chars:
if char in vowels:
only_vowels.append(char)
# Output: ['e', 'o']
List comprehension:
chars = ['t', 'e', 'c', 'h', 'y', 'o', 'w', 'l', 's']
vowels = ['a', 'e', 'i', 'o', 'u']
only_vowels = [char for char in chars if char in vowels]
# Output: ['e', 'o']
Example: Filter Even Numbers
numbers = range(1, 21)
# Get even numbers only
evens = [n for n in numbers if n % 2 == 0]
# Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
If-Else in List Comprehensions
Use conditional expressions for transformations:
[true_expr if condition else false_expr for item in iterable]
Example: Classify Numbers
numbers = [1, 2, 3, 4, 5]
labels = ['even' if n % 2 == 0 else 'odd' for n in numbers]
# Output: ['odd', 'even', 'odd', 'even', 'odd']
Example: Cap Values
prices = [12, 45, 78, 23, 99, 15]
capped = [min(price, 50) for price in prices]
# Output: [12, 45, 50, 23, 50, 15]
Nested List Comprehensions
For working with nested data structures:
# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Example: Create a Matrix
# 3x3 multiplication table
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Performance Benefits
List comprehensions are often faster than traditional loops because:
- No
.append()calls - Appending has overhead - Optimized bytecode - Python optimizes list comprehensions
- Single expression - Less interpreter overhead
Benchmark Example
import timeit
numbers = range(10000)
# Traditional loop
def with_loop():
result = []
for n in numbers:
result.append(n * 2)
return result
# List comprehension
def with_comprehension():
return [n * 2 for n in numbers]
# List comprehension is typically 20-30% faster
print(timeit.timeit(with_loop, number=1000))
print(timeit.timeit(with_comprehension, number=1000))
When NOT to Use List Comprehensions
Avoid Complex Comprehensions
Bad - too complex:
# Don't do this!
result = [
process(x, y)
for x in data
if validate(x)
for y in get_related(x)
if check_condition(x, y)
]
Better - use a regular loop:
result = []
for x in data:
if validate(x):
for y in get_related(x):
if check_condition(x, y):
result.append(process(x, y))
Guidelines
- Good: 1-2 loops with 0-1 conditions
- Avoid: 3+ loops or complex conditions
- Never: Side effects in comprehensions
Dictionary and Set Comprehensions
The same pattern works for dicts and sets:
Dictionary Comprehension
names = ['alice', 'bob', 'charlie']
name_lengths = {name: len(name) for name in names}
# Output: {'alice': 5, 'bob': 3, 'charlie': 7}
Set Comprehension
numbers = [1, 2, 2, 3, 3, 3, 4]
unique_squares = {n**2 for n in numbers}
# Output: {1, 4, 9, 16}
Practical Examples
Parse CSV-like Data
data = "John,25,Engineer;Jane,30,Designer;Bob,35,Manager"
records = [
{'name': r.split(',')[0], 'age': int(r.split(',')[1])}
for r in data.split(';')
]
Filter Files by Extension
import os
files = os.listdir('.')
python_files = [f for f in files if f.endswith('.py')]
Word Frequency
text = "the quick brown fox jumps over the lazy dog"
words = text.split()
word_freq = {word: words.count(word) for word in set(words)}
Summary
| Feature | Traditional Loop | List Comprehension |
|---|---|---|
| Lines of code | Multiple | Single |
| Readability | Verbose | Concise |
| Performance | Slower | Faster |
| Flexibility | More | Limited |
Conclusion
List comprehensions are a Pythonic way to:
- Create lists from iterables
- Filter and transform data
- Write more readable code
Key Takeaways:
- Use for simple transformations (1-2 loops, 0-1 conditions)
- Avoid for complex logic - use regular loops instead
- Remember dict and set comprehensions too
- Performance is often 20-30% better than loops
Advertisement
Moshiour Rahman
Software Architect & AI Engineer
Enterprise software architect with deep expertise in financial systems, distributed architecture, and AI-powered applications. Building large-scale systems at Fortune 500 companies. Specializing in LLM orchestration, multi-agent systems, and cloud-native solutions. I share battle-tested patterns from real enterprise projects.
Related Articles
Full Stack for Backend Devs: Reactive UIs with FastAPI & HTMX (No React Required)
Tired of 'npm install' and complex state management? Learn how to build modern, dynamic user interfaces using only Python, HTML, and HTMX.
PythonAI Agents Fundamentals: Build Your First Agent from Scratch
Master AI agents from the ground up. Learn the agent loop, build a working agent in pure Python, and understand the foundations that power LangGraph and CrewAI.
PythonTool-Using AI Agents: Web Search, Code Execution & API Integration
Build powerful AI agents with real-world tools. Learn to integrate web search, execute code safely, work with files, and connect to external APIs using LangGraph.
Comments
Comments are powered by GitHub Discussions.
Configure Giscus at giscus.app to enable comments.