Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Organise the chaos
EXPERIMENT 14 / 101

Build a collection in one thought.

Transform and filter data with a compact, readable expression.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

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.

comprehensions.py
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)
↳ EXPECTED OUTPUT
[12, 8]
[0.2, 0.13333333333333333]

03 Under the hood

  1. 1

    The first comprehension keeps only durations below thirty minutes. It creates a new list; durations is unchanged.

  2. 2

    The second transforms each retained value from minutes to hours. Filtering and transformation are different steps, and splitting them can improve clarity.

  3. 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

A SMALL MISSION

From numbers 1 through 6, build a list containing only the squares of even numbers.

Reveal one possible solution +
one_possible_solution.py
squares = [number ** 2 for number in range(1, 7) if number % 2 == 0]
print(squares)

05 Check your signal

QUICK SIGNAL CHECK

What does [n * 2 for n in [1, 3]] produce?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.