List Comprehensions
Learn how to build lists in one elegant line using Python's powerful comprehension syntax.
Imagine you have a list of numbers and you want to double every one of them. The long way is to write a for loop, create an empty list, and append each result. Python gives you a shortcut that does all of this in one line: the list comprehension.
List comprehensions are one of Python's most loved features. They make your code shorter, more readable, and often faster. Let's build them up from scratch.
See it in action
— step through the idea, then dive into the details below.Build Lists in One Line
A list comprehension turns a multi-line for loop into a single, readable expression. It's one of Python's most loved shortcuts.
#The Problem: Building Lists with a Loop
Here is the classic pattern you already know — a for loop that builds a new list:
numbers = [1, 2, 3, 4, 5]
doubled = []
for n in numbers:
doubled.append(n * 2)
print(doubled)This works perfectly well. But Python lets you say the exact same thing much more concisely.
#Your First List Comprehension
Think of it like an English sentence
A list comprehension reads almost like plain English: *"give me `n 2 for each n in numbers`"**.
In Python that becomes: [n * 2 for n in numbers]
numbers = [1, 2, 3, 4, 5]
doubled = [n * 2 for n in numbers]
print(doubled)The structure is: [expression for item in iterable]
- expression — what you want each element to look like
- item — the variable name for each element as you loop
- iterable — the source list (or any sequence)
The square brackets [ ] tell Python the result should be a list.
#Transforming Values
You can put any expression before the for. Here are a few quick examples:
words = ["hello", "world", "python"]
# Uppercase every word
upper = [w.upper() for w in words]
print(upper)
# Get the length of each word
lengths = [len(w) for w in words]
print(lengths)#Filtering with if
You can add an if condition at the end to filter which items get included. Only items where the condition is True make it into the new list.
numbers = [-3, -1, 0, 2, 4, 7]
# Keep only the positive numbers
positives = [x for x in numbers if x > 0]
print(positives)You can combine a transform and a filter at the same time:
numbers = [-3, -1, 0, 2, 4, 7]
# Double only the positive numbers
doubled_positives = [x * 2 for x in numbers if x > 0]
print(doubled_positives)if at the end vs. if...else in the middle
There are two different placements of if, and they mean different things:
- Filter (end):
[x for x in nums if x > 0]— skips items that fail - Conditional value (middle):
[x if x > 0 else 0 for x in nums]— keeps all items but changes their value
The second form uses a ternary expression before the for. Mixing them up is a very common beginner mistake!
numbers = [-3, -1, 0, 2, 4]
# Replace negatives with 0, keep positives as-is
clamped = [x if x > 0 else 0 for x in numbers]
print(clamped)#Dict and Set Comprehensions
The same idea works for dictionaries (use curly braces {} with a colon) and sets (use curly braces without a colon).
words = ["apple", "banana", "cherry"]
# Dict comprehension: word -> its length
length_map = {w: len(w) for w in words}
print(length_map)
# Set comprehension: unique first letters
first_letters = {w[0] for w in words}
print(first_letters)#Nested Comprehensions (a Quick Look)
You can nest a comprehension inside another to flatten or process 2D data. Use this sparingly — if it gets hard to read, a regular loop is better.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Flatten all rows into one list
flat = [num for row in matrix for num in row]
print(flat)Readability is king
List comprehensions are great for simple transforms and filters. If your comprehension spans more than one line in your head, or needs two nested loops, just use a regular for loop. Clear code always beats clever code.
#Side-by-Side: Loop vs. Comprehension
# These two produce the exact same result:
sentences = ["hello world", "python is fun", "keep it simple"]
# For-loop version
result_loop = []
for s in sentences:
if len(s) < 15:
result_loop.append(s.title())
# Comprehension version
result_comp = [s.title() for s in sentences if len(s) < 15]
print(result_loop)
print(result_comp)What does this comprehension produce? ```python [x ** 2 for x in range(5) if x % 2 == 0] ```
Key takeaways
- `[expr for item in iterable]` builds a new list by applying an expression to every element.
- Add `if condition` at the end to filter items — only matching items are included.
- Dict comprehensions use `{k: v for ...}` and set comprehensions use `{v for ...}`.
- Nested comprehensions can flatten 2D data, but keep readability in mind.
- When a comprehension gets complicated, a plain `for` loop is always a valid and clear alternative.
What does this code print?
numbers = [1, 2, 3, 4, 5]
squares = [n ** 2 for n in numbers if n % 2 != 0]
print(squares)This code should build a list of uppercase words, but it has a bug. What is wrong?
words = ["hello", "world", "python"]
upper = [w.upper for w in words]
print(upper)Complete the comprehension so it produces a list of Fahrenheit values from the Celsius list.
celsius = [0, 20, 100] fahrenheit = [ for c in celsius] print(fahrenheit)
Put these lines in the right order to build a list of lengths for words longer than 4 characters.
print(long_lengths)
long_lengths = [len(w) for w in words if len(w) > 4]
words = ["hi", "apple", "cat", "banana"]
You have a list of temperatures in Celsius: [-10, 0, 15, 22, 37, 100].
- Use a list comprehension to convert every temperature to Fahrenheit. Formula:
F = C * 9/5 + 32. - Use another comprehension to keep only the Fahrenheit values that are above 60°F.
- Bonus: build a dict that maps each original Celsius value to its Fahrenheit equivalent.
Try it live — edit the code and hit Run to execute real Python: