← Back to Python, page 1

python-0003 · Easy fresher

Explain list comprehensions with examples, including a filter and a nested loop.

A list comprehension builds a list from an iterable in one expression: [expression for item in iterable if condition]. It is usually clearer and faster than an equivalent loop with append. Nested for clauses read left to right like nested loops, and dict and set comprehensions use the same syntax with braces.

Full answer
python
nums = [1, 2, 3, 4, 5, 6]
print([n * n for n in nums])
print([n * n for n in nums if n % 2 == 0])
print([(c, s) for c in ["red", "blue"] for s in ["S", "M"]])
words = ["apple", "kiwi", "avocado"]
print({w: len(w) for w in words})
print(sorted({w[0] for w in words}))
print(sum(n * n for n in nums))

Output:

text
[1, 4, 9, 16, 25, 36]
[4, 16, 36]
[('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]
{'apple': 5, 'kiwi': 4, 'avocado': 7}
['a', 'k']
91

The first comprehension squares every number; the second keeps only even numbers before squaring, since the if filters items. The pairs example has two for clauses, which run like an outer loop over colours and an inner loop over sizes. The dict comprehension maps each word to its length, and the set comprehension removes duplicate first letters; it is sorted before printing because set order is not stable between runs, which the double-run check here caught.

Guidelines:

  • Keep comprehensions short; if one needs several conditions and nested loops, a normal loop is easier to read.
  • A conditional expression in the output part is different from a filter: [x if x > 0 else 0 for x in nums] keeps every item.
  • Use a generator expression (x * x for x in nums) when the result is consumed once, such as by sum(), to avoid building a list.
python
nums = [1, 2, 3, 4, 5, 6]
print([n * n for n in nums])
print([n * n for n in nums if n % 2 == 0])
print([(c, s) for c in ["red", "blue"] for s in ["S", "M"]])
words = ["apple", "kiwi", "avocado"]
print({w: len(w) for w in words})
print(sorted({w[0] for w in words}))
print(sum(n * n for n in nums))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • [expr for x in it if cond]
  • Filters drop items; conditional expressions transform them
  • Nested for clauses read left to right
  • Dict and set comprehensions exist
  • Generators avoid building lists

Common mistakes

  • Writing very long nested comprehensions
  • Confusing filter if with if-else in the expression

Follow-ups

  • How would you flatten a list of lists?
  • When is a generator expression better?

Tips

  • Read nested clauses as nested loops