الانتقال إلى المحتوى الرئيسي
eLearner.app
الوحدة 6 · الدرس 1 من 421/36 في الدورة~12 min
دروس الوحدة (1/4)

قائمة الفهم

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

تمرين#python.m6.l1.e1
المحاولات: 0جارٍ التحميل…

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

جارٍ تحميل المحرر…
إظهار التلميح

if n % 2 == 0 at the end.

الحل متاح بعد 3 من المحاولات

Review exercise

تمرين#python.m6.l1.e2
المحاولات: 0جارٍ التحميل…

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)`.

جارٍ تحميل المحرر…
إظهار التلميح

Two separate comprehensions.

الحل متاح بعد 3 من المحاولات

Additional challenge

تمرين#python.m6.l1.e3
المحاولات: 0جارٍ التحميل…

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.

جارٍ تحميل المحرر…
إظهار التلميح

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

الحل متاح بعد 3 من المحاولات