Python List Comprehensions: From Basics to Advanced Patterns
Master Python list comprehensions with clear examples. Learn when to use them, when to avoid them, and how they compare to traditional loops and map/filter.
Learn2Code Team
January 26, 2026
What Is a List Comprehension?
A list comprehension is a concise way to create a list in Python. Instead of writing a multi-line loop, you express the entire operation in a single line.
1# Traditional loop2squares = []3for x in range(10):4 squares.append(x ** 2)5 6# List comprehension -- same result in one line7squares = [x ** 2 for x in range(10)]8# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]Both produce the same list. The comprehension is shorter, more readable (once you learn the syntax), and often faster because Python optimizes comprehensions internally.
The Basic Pattern
Every list comprehension follows this structure:
1[expression for item in iterable]- expression -- what you want each element to be
- item -- the variable representing each element
- iterable -- the source of data (list, range, string, etc.)
1# Double each number2doubled = [x * 2 for x in [1, 2, 3, 4, 5]]3# [2, 4, 6, 8, 10]4 5# Get lengths of words6words = ["hello", "world", "python"]7lengths = [len(w) for w in words]8# [5, 5, 6]9 10# Convert to uppercase11names = ["alice", "bob", "charlie"]12upper_names = [name.upper() for name in names]13# ["ALICE", "BOB", "CHARLIE"]Adding a Filter with if
You can filter elements by adding a condition:
1[expression for item in iterable if condition]1# Keep only even numbers2evens = [x for x in range(20) if x % 2 == 0]3# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]4 5# Words longer than 4 characters6words = ["hi", "hello", "hey", "howdy", "greetings"]7long_words = [w for w in words if len(w) > 4]8# ["hello", "howdy", "greetings"]9 10# Positive numbers only11numbers = [-3, -1, 0, 2, 5, -7, 8]12positive = [n for n in numbers if n > 0]13# [2, 5, 8]Conditional Expressions (if-else)
To transform values differently based on a condition, use a conditional expression in the expression part:
1[expression_if_true if condition else expression_if_false for item in iterable]Note the different position -- this goes before for, not after it.
1# Label numbers as even or odd2labels = ["even" if x % 2 == 0 else "odd" for x in range(6)]3# ["even", "odd", "even", "odd", "even", "odd"]4 5# Cap values at a maximum6numbers = [5, 12, 3, 18, 7, 25]7capped = [min(n, 10) for n in numbers]8# [5, 10, 3, 10, 7, 10]9 10# Replace negatives with zero11values = [3, -1, 4, -5, 9]12cleaned = [v if v >= 0 else 0 for v in values]13# [3, 0, 4, 0, 9]Nested Loops in Comprehensions
You can use multiple for clauses. The loops execute in the order they appear, left to right.
1# All combinations of two lists2colors = ["red", "blue"]3sizes = ["S", "M", "L"]4combos = [(c, s) for c in colors for s in sizes]5# [("red", "S"), ("red", "M"), ("red", "L"),6# ("blue", "S"), ("blue", "M"), ("blue", "L")]7 8# Flatten a 2D list9matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]10flat = [num for row in matrix for num in row]11# [1, 2, 3, 4, 5, 6, 7, 8, 9]The equivalent loop for the flatten example:
1flat = []2for row in matrix:3 for num in row:4 flat.append(num)Dictionary and Set Comprehensions
The same pattern works for dictionaries and sets.
Dictionary Comprehension
1{key_expression: value_expression for item in iterable}1# Square mapping2squares = {x: x ** 2 for x in range(6)}3# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}4 5# Word lengths6words = ["hello", "world", "python"]7word_lengths = {w: len(w) for w in words}8# {"hello": 5, "world": 5, "python": 6}9 10# Invert a dictionary11original = {"a": 1, "b": 2, "c": 3}12inverted = {v: k for k, v in original.items()}13# {1: "a", 2: "b", 3: "c"}Set Comprehension
1{expression for item in iterable}1# Unique first letters2names = ["Alice", "Bob", "Anna", "Charlie", "Andy"]3first_letters = {name[0] for name in names}4# {"A", "B", "C"}When to Use Comprehensions (and When Not To)
Use Comprehensions When
- Transforming data: applying a function to each element
- Filtering data: selecting elements that meet a criteria
- The logic fits on one readable line
- You need a new list/dict/set from existing data
Avoid Comprehensions When
- The logic is complex: if you need multiple conditions or nested transformations, a regular loop is clearer
- You have side effects: if the expression does something other than produce a value (printing, writing to a file, modifying external state), use a loop
- Readability suffers: a comprehension that takes 3 lines is not a comprehension -- it is a compressed loop
1# Too complex -- use a regular loop instead2result = [3 transform(x)4 for x in data5 if validate(x)6 and x.status == "active"7 and x.created > cutoff_date8]9 10# Clearer as a loop11result = []12for x in data:13 if validate(x) and x.status == "active" and x.created > cutoff_date:14 result.append(transform(x))Comprehensions vs map() and filter()
Python also has map() and filter() functions that do similar things. How do they compare?
1numbers = [1, 2, 3, 4, 5]2 3# map + filter4evens_doubled = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, numbers)))5 6# List comprehension -- same result, more readable7evens_doubled = [x * 2 for x in numbers if x % 2 == 0]For most cases, list comprehensions are more Pythonic and readable than map and filter. The exception is when you already have a named function:
1# map with a named function is clean2names = ["alice", "bob", "charlie"]3upper_names = list(map(str.upper, names))4 5# Comprehension is equally clean here6upper_names = [name.upper() for name in names]Performance Considerations
List comprehensions are generally faster than equivalent for loops because Python optimizes them internally. The speedup typically ranges from 10-30% for simple operations.
However, for very large datasets, consider using generator expressions instead. A generator produces values lazily (one at a time) rather than creating the entire list in memory:
1# List comprehension -- creates entire list in memory2squares = [x ** 2 for x in range(1_000_000)]3 4# Generator expression -- produces values on demand5squares_gen = (x ** 2 for x in range(1_000_000))Use parentheses instead of brackets for a generator. Generators are ideal when you only need to iterate once or when the data is too large to fit in memory.
Common Patterns
Extract Data from Objects
1users = [2 {"name": "Alice", "age": 30},3 {"name": "Bob", "age": 25},4 {"name": "Charlie", "age": 35},5]6 7names = [u["name"] for u in users]8# ["Alice", "Bob", "Charlie"]9 10adults = [u for u in users if u["age"] >= 30]11# [{"name": "Alice", "age": 30}, {"name": "Charlie", "age": 35}]String Processing
1# Remove whitespace from each line2lines = [" hello ", " world ", " python "]3cleaned = [line.strip() for line in lines]4# ["hello", "world", "python"]5 6# Split CSV into rows7csv_data = "alice,30\nbob,25\ncharlie,35"8rows = [line.split(",") for line in csv_data.split("\n")]9# [["alice", "30"], ["bob", "25"], ["charlie", "35"]]Working with Files
1# Read non-empty lines from a file2with open("data.txt") as f:3 lines = [line.strip() for line in f if line.strip()]Practice List Comprehensions
The best way to master comprehensions is to practice converting loops into comprehensions and back. For each exercise, try both approaches:
- Create a list of the first 10 cube numbers
- Filter a list of words to keep only those starting with a vowel
- Create a dictionary mapping numbers 1-10 to their squares
- Flatten a list of lists into a single list
Start with our interactive Python exercises to practice list comprehensions and other Python patterns. Keep our Python cheatsheet bookmarked for quick syntax reference.
Related Reading
- Understanding Functions in Programming -- comprehensions often use function calls in their expressions
- JavaScript Array Methods: map, filter, reduce -- the JavaScript equivalents of Python comprehensions
- How to Practice Coding Effectively -- use spaced repetition to make comprehension syntax automatic
