Data StructuresIntermediate8 min26 / 63

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

Visual walkthrough1 / 5
1

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.

Same result as a loop — just faster to write and often easier to read.

#The Problem: Building Lists with a Loop

Here is the classic pattern you already know — a for loop that builds a new list:

The traditional for-loop approach to building a 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

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]

The same result as the loop above, but in one line
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:

Comprehensions work with strings and any expression
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.

The if clause acts as a filter — failing items are skipped
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:

Filter first, then transform — all in one expression
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)
Common mistake

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!

ternary expression BEFORE the for — every item is included
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).

Dict uses {key: value for ...}, set uses {value for ...}
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.

Read left-to-right: 'for each row, for each num in that row'
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)
Tip

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

Both approaches produce identical results
# 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)
Quick check

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.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
numbers = [1, 2, 3, 4, 5]
squares = [n ** 2 for n in numbers if n % 2 != 0]
print(squares)
Fix the bug#2

This code should build a list of uppercase words, but it has a bug. What is wrong?

fix-bug
words = ["hello", "world", "python"]
upper = [w.upper for w in words]
print(upper)
Fill in the blank#3

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)
Reorder the lines#4

Put these lines in the right order to build a list of lengths for words longer than 4 characters.

1
print(long_lengths)
2
long_lengths = [len(w) for w in words if len(w) > 4]
3
words = ["hi", "apple", "cat", "banana"]
Your turn
Practice exercise

You have a list of temperatures in Celsius: [-10, 0, 15, 22, 37, 100].

  1. Use a list comprehension to convert every temperature to Fahrenheit. Formula: F = C * 9/5 + 32.
  2. Use another comprehension to keep only the Fahrenheit values that are above 60°F.
  3. 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:

solution.py · editable