Build a collection in one thought.
Transform and filter data with a compact, readable expression.
01 The idea
A list comprehension builds a new list by evaluating an expression for each item in an iterable. An optional if clause filters items. Read it as: produce this value, for each item, if this condition holds. Keep it simple enough to understand at a glance.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
durations = [12, 35, 8, 50]
quick_tasks = [minutes for minutes in durations if minutes < 30]
hours = [minutes / 60 for minutes in quick_tasks]
print(quick_tasks)
print(hours)[12, 8] [0.2, 0.13333333333333333]
03 Under the hood
- 1
The first comprehension keeps only durations below thirty minutes. It creates a new list; durations is unchanged.
- 2
The second transforms each retained value from minutes to hours. Filtering and transformation are different steps, and splitting them can improve clarity.
- 3
Dictionary and set comprehensions use a similar pattern with braces. For complex branching or side effects, an ordinary loop is usually easier to maintain.
04 Your turn, builder
From numbers 1 through 6, build a list containing only the squares of even numbers.
Reveal one possible solution +
squares = [number ** 2 for number in range(1, 7) if number % 2 == 0]
print(squares)05 Check your signal
What does [n * 2 for n in [1, 3]] produce?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.