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.
# 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
[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
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:
[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:
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/elsebranches → 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:
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
Given `nums = [1, 2, 3, 4, 5, 6]`, build `even_squares` with the squares of just the even numbers. Evaluate `even_squares`.
Show hint
if n % 2 == 0 at the end.
Solution available after 3 attempts
Review exercise
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)`.
Show hint
Two separate comprehensions.
Solution available after 3 attempts
Additional challenge
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.
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