A list comprehension builds a new list in a single readable line: “give me the square of each number” becomes [n * n for n in nums]. Comprehensions replace the common pattern of an empty list, a loop and append(). Python has the same idea for dictionaries and sets, and a lazy version called a generator expression.
In this lesson you will learn
- The basic comprehension syntax
- Filtering with
ifand choosing values withif ... else - Nested comprehensions for 2D lists
- Dictionary and set comprehensions
- Generator expressions, and when a plain loop is better
Mapping and Filtering
The pattern is [expression for item in iterable if condition].
nums = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in nums]
evens = [n for n in nums if n % 2 == 0]
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
print(squares)
print(evens)
print(labels)
# the same as a plain loop
result = []
for n in nums:
if n % 2 == 0:
result.append(n)
print(result == evens)
Output
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
['odd', 'even', 'odd', 'even', 'odd', 'even']
True
[n * n for n in nums]transforms every item.[n for n in nums if n % 2 == 0]keeps only items that pass the test. Theifgoes at the end.["even" if ... else "odd" for n in nums]picks one of two values for every item. Thisif ... elsegoes at the start, because it is part of the expression.- The plain loop at the bottom produces the same list, which shows what the comprehension does for you.
Nested, Dict, Set and Generator Comprehensions
words = ["Python", "is", "fun", "and", "useful"]
print([w.upper() for w in words if len(w) > 2])
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [x for row in matrix for x in row]
print(flat)
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed)
lengths = {w: len(w) for w in words}
print(lengths)
unique_first = {w[0].lower() for w in words}
print(sorted(unique_first))
total = sum(n * n for n in range(1, 4)) # generator expression
print(total)
Output
['PYTHON', 'FUN', 'AND', 'USEFUL']
[1, 2, 3, 4, 5, 6]
[[1, 4], [2, 5], [3, 6]]
{'Python': 6, 'is': 2, 'fun': 3, 'and': 3, 'useful': 6}
['a', 'f', 'i', 'p', 'u']
14
- Flattening:
[x for row in matrix for x in row]reads in the same order as two nestedforloops: outer first, inner second. - Transposing: a comprehension inside a comprehension builds a list of lists.
- Dict comprehension:
{key: value for ...}. Set comprehension:{value for ...}, which removes duplicates. - Generator expression: round brackets, as in
sum(n * n for n in ...), produce values one at a time without building a list. See Iterators and Generators.
When Not to Use a Comprehension
Comprehensions are for building a collection. If the logic needs several steps, try/except, or prints something, a normal for loop is clearer. A good rule: if the comprehension does not fit comfortably on one or two lines, rewrite it as a loop.
Common Mistakes
- Putting the filter
ifat the front without anelse, which is a syntax error. - Using a comprehension only for side effects, like
[print(x) for x in items]. It builds a useless list ofNones; use a loop. - Getting nested loop order backwards when flattening.
Practice Exercises
Exercise 1. From [" rafi ", "NILA", " Tanim"], make a list of clean, capitalised names.
Show answer
names = [" rafi ", "NILA", " Tanim"]
print([n.strip().capitalize() for n in names]) # ['Rafi', 'Nila', 'Tanim']
Exercise 2. Build a dictionary mapping each number from 1 to 5 to its cube.
Show answer
print({n: n ** 3 for n in range(1, 6)})
Frequently Asked Questions
Are list comprehensions faster than loops?
Usually a little, because the appending happens inside Python’s internals. Choose them mainly for readability, though.
Is there a tuple comprehension?
No. Round brackets create a generator expression; wrap it in tuple(...) to get a tuple.
Summary
[expr for x in items if cond]maps and filters in one line.a if cond else bat the front chooses a value per item.- Curly braces give dict and set comprehensions; round brackets give a generator.
- Use a loop when the logic gets long.
