List comprehensions

Build a useful list

Lesson 6 of 20 · 8 min · Module 2: Loops & functions

A list comprehension is a compact way to build a new list from an existing collection. It combines iteration, optional filtering, and an output expression.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Read a comprehension from its loop
  • Add a filter without changing the order
  • Prefer a readable loop for more complex work

The idea

The pattern is [expression for item in items if condition]. Leave out the condition when you want to transform every item.

scores = [30, 80, 50]
passing = [score for score in scores if score >= 50]
print(passing) # [80, 50]

01Translate to a familiar loop

The comprehension corresponds to creating an empty list, looping through scores, checking each score, and appending the values that pass. The result is a new list.

02Keep the expression small

A comprehension is useful when one expression and one condition describe the work. If you need several actions or complicated error handling, a regular for loop is often clearer.

Your turn

Define passing_scores(scores) to return a new list containing only scores at least 50. Keep their input order and leave the original list unchanged.

What the checks look for

  • Selects passing scores in order
  • Handles empty and failing lists
  • Returns a new list
Try it in the editor →

Take this with you

A comprehension describes the values you want in the result.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →