Skip to main content
eLearner.app
Module 6 · Lesson 1 of 421/36 in the course~12 min
Module lessons (1/4)

List comprehension

A list comprehension is an expression that builds a list by applying a transformation (and optionally a filter) to an iterable. It's the Pythonic way to write for + append on a single line.

Python
# stile imperativo (verboso)
quadrati = []
for n in range(5):
    quadrati.append(n * n)

# stile pythonico
quadrati = [n * n for n in range(5)]
# [0, 1, 4, 9, 16]

Full syntax

Python
[espressione for elemento in iterabile if condizione]
  • expression: what to put into the resulting list
  • for element in iterable: source loop
  • if condition (optional): keeps only the elements that match
Python
pari = [n for n in range(10) if n % 2 == 0]
# [0, 2, 4, 6, 8]

maiuscole = [p.upper() for p in ["ciao", "mondo"]]
# ['CIAO', 'MONDO']

lunghe = [p for p in ["a", "bb", "ccc", "dddd"] if len(p) >= 3]
# ['ccc', 'dddd']

if/else inside the expression (ternary)

To transform conditionally (rather than filter), use the ternary expression BEFORE the for:

Python
[n if n > 0 else 0 for n in [-2, -1, 0, 1, 2]]
# [0, 0, 0, 1, 2]

Multi-for: cartesian product

You can nest multiple for clauses:

Python
coppie = [(x, y) for x in range(3) for y in range(2)]
# [(0,0), (0,1), (1,0), (1,1), (2,0), (2,1)]

The order of the for clauses is "outer-before-inner", as if they were nested loops.

When NOT to use a comprehension

  • Complex logic with many nested if/else branches → use an explicit loop.
  • Side effects (print, file writes) → loop, not comprehension.
  • More than 2 nested levels → an explicit named loop is almost always better.

Nested list comprehensions

You can chain multiple for loops inside a single list comprehension. For instance, to flatten a matrix (a list of lists) into a single flat list, you can write:

Python
matrix = [[1, 2], [3, 4]]
flat = [item for row in matrix for item in row]
# result: [1, 2, 3, 4]

The order of the loops mirrors exactly the nesting order of traditional for loops.

Try it

Exercise#python.m6.l1.e1
Attempts: 0Loading…

Given `nums = [1, 2, 3, 4, 5, 6]`, build `even_squares` with the squares of just the even numbers. Evaluate `even_squares`.

Loading editor…
Show hint

if n % 2 == 0 at the end.

Solution available after 3 attempts

Review exercise

Exercise#python.m6.l1.e2
Attempts: 0Loading…

Given `words = ['Ciao', 'Mondo', 'Python', 'Java']`, build `lengths` with the length of EVERY word, and `short_words` with only the words shorter than 5 characters. Evaluate `(lengths, short_words)`.

Loading editor…
Show hint

Two separate comprehensions.

Solution available after 3 attempts

Additional challenge

Exercise#python.m6.l1.e3
Attempts: 0Loading…

Use a list comprehension to calculate the squares of only the even integers between 1 and 10 inclusive. Store the list in `even_squares` and evaluate it.

Loading editor…
Show hint

Use range(1, 11) to iterate, if x % 2 == 0 to filter, and x**2 as the expression.

Solution available after 3 attempts