Comprehensions, Lambda & Functional Tools
Chapter 8 built dictionaries and sets by looping and building up a result one step at a time — an empty container, a for loop, and an .append() or assignment inside it. That pattern is so common that Python gives it a shorter, single-line spelling: a comprehension. This chapter also introduces lambda, a way to write a tiny, throwaway function in a single line, and the functional tools — map(), filter(), sorted() — that put it to work.
How to read this chapter
- Every comprehension is a loop in disguise. If a comprehension ever looks confusing, mentally expand it back into the
forloop that means the same thing. - Read the example first. The code mirrors real situations like cleaning signups, filtering datasets, and ranking records.
- Concise isn't always better. This chapter is as much about when not to use a comprehension as when to use one.
lambda for small one-off logic, this is the syntax that makes everyday Python code read the way experienced developers actually write it.
1. List comprehensions
- A list comprehension builds a new list from an existing iterable, in one line.
- The basic shape is
[expr for item in iterable]. - Adding
if conditionat the end filters out items you don't want.
for loop that does nothing but build a new list.
[expr for item in iterable]. It takes every
item in iterable, computes expr
from it, and collects the results into a brand-new list — the exact
same job as a for loop with an empty list and
.append(), just written more compactly.
numbers = [1, 2, 3, 4, 5]
# the for-loop version you already know from Chapter 5
squares_loop = []
for n in numbers:
squares_loop.append(n ** 2)
# the exact same result, as a list comprehension
squares_comp = [n ** 2 for n in numbers]
print(squares_loop) # [1, 4, 9, 16, 25]
print(squares_comp) # [1, 4, 9, 16, 25]
Both versions do exactly the same work, in exactly the same order — the comprehension is not a different kind of loop, just a shorter way to write the same one:
for-loop version comprehension version
---------------- ---------------------
squares = [] squares = [n ** 2
for n in numbers: for n in numbers]
squares.append(n ** 2)
Both produce: [1, 4, 9, 16, 25]
A comprehension can also filter, the same way an if
inside a for loop would — adding
if condition at the end keeps only the items where the
condition is True:
numbers = [1, 2, 3, 4, 5]
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4]
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
print(even_squares) # [4, 16]
Read that shape left to right: n ** 2 is what goes into
the new list, for n in numbers says where each
n comes from, and if n % 2 == 0 says which
values of n are allowed through at all. The equivalent
loop makes the same three parts explicit, just spread across more
lines:
numbers = [1, 2, 3, 4, 5]
even_squares = []
for n in numbers:
if n % 2 == 0:
even_squares.append(n ** 2)
print(even_squares) # [4, 16]
Go Deeper: a comprehension always creates a new list
[n for n in numbers] never changes numbers
itself — it always builds and returns a brand-new list, the same
way slicing (Chapter 6) never changes the original string or list.
If you need to change a list in place, a plain for
loop with .append() or index assignment is still the
right tool.
- A list comprehension,
[expr for item in iterable], builds a new list in one line — the same logic as aforloop with.append(). - Adding
if conditionat the end filters which items make it into the new list. - A comprehension never modifies the original iterable — it always returns a new list.
2. Dict & set comprehensions
- A dict comprehension,
{k: v for ...}, builds a new dictionary. - A set comprehension,
{expr for ...}, builds a new set of unique values. - Pick the container that matches the shape of the result you actually need.
A dict comprehension follows the same shape as a list comprehension,
just with a key: value pair in front instead of a single
expression:
names = ["Priya", "Amir", "Zoe"]
name_lengths = {name: len(name) for name in names}
print(name_lengths) # {'Priya': 5, 'Amir': 4, 'Zoe': 3}
{key_expr: value_expr for item in
iterable}, builds a new dictionary from an iterable in one
line — the dictionary version of Chapter 8's
counts[word] = counts.get(word, 0) + 1 loop, but for
cases where every entry can be computed directly, with no running
state needed.
It works just as well looping over an existing dictionary's
.items() — transforming every value while keeping the
same keys:
prices = {"coffee": 3.50, "tea": 2.75, "juice": 4.00}
discounted = {drink: round(price * 0.9, 2) for drink, price in prices.items()}
print(discounted) # {'coffee': 3.15, 'tea': 2.48, 'juice': 3.6}
A set comprehension drops the key: part entirely — just
curly braces around a single expression, exactly like the set
literals from Chapter 8, except the values now come from a loop
instead of being typed out by hand:
words = ["the", "cat", "sat", "on", "the", "mat"]
unique_lengths = {len(word) for word in words}
print(unique_lengths) # {2, 3} — duplicates collapse automatically
{expr for item in iterable}, builds
a new set the same way a list comprehension builds a list — except
duplicate results collapse into one, since a set can never hold the
same value twice (Chapter 8).
That collapsing behavior is exactly why set comprehensions show up in real cleanup code — normalizing a batch of emails to lowercase naturally reveals which ones were actually duplicates all along:
emails = ["a@x.com", "A@X.COM", "b@x.com"]
unique_emails = {email.lower() for email in emails}
print(len(unique_emails)) # 2 — "a@x.com" and "A@X.COM" were the same address
Go Deeper: both accept the same if filter as list comprehensions
Dict and set comprehensions support the exact same trailing
if condition as list comprehensions —
{k: v for k, v in prices.items() if v > 3} keeps
only the entries priced above 3. The filter always goes at the
end, after the loop, no matter which container you're building.
- A dict comprehension,
{k: v for item in iterable}, builds a dictionary in one line — the direct-computation counterpart to Chapter 8's tallying loop. - A set comprehension,
{expr for item in iterable}, builds a set, automatically collapsing duplicate results. - Choose the container by what the result needs to do: named lookups call for a dict, guaranteed uniqueness calls for a set.
3. Nested comprehensions & readability limits
- A comprehension can loop over a nested list (a 2D grid), the same way nested
forloops do. - Every extra
fororifyou add makes a comprehension harder to read, not easier. - Readability beats cleverness — a comprehension that needs explaining should just be a loop.
for and, at most, one if — beyond that, write the loop out instead.
A 2D grid — a list of lists, from Chapter 7 — can be flattened into a
single list with two for clauses in one comprehension,
read left to right in the same order as nested for
loops:
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
flat = [value for row in grid for value in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
for clause, read in the same order they'd appear as
nested loops. [value for row in grid for value in row]
means "for each row in grid, then for each
value in that row" — outer loop first, inner
loop second, exactly left to right.
A comprehension can also build a new grid instead of flattening one, by nesting one comprehension inside another — this doubles every value while keeping the original 2D shape:
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
doubled_grid = [[value * 2 for value in row] for row in grid]
print(doubled_grid)
# [[2, 4, 6], [8, 10, 12], [14, 16, 18]]
That last example is close to the readability edge already — a comprehension nested inside another comprehension takes real effort to parse. Once a comprehension needs a second condition, a computed value used more than once, or a nested comprehension inside it, the "one-line" version stops being the readable one:
records = [
{"name": "Priya", "scores": [91, 85, 78]},
{"name": "Amir", "scores": [60, 55]},
]
# technically valid, but the average is recomputed and hard to spot at a glance
passing_names = [r["name"] for r in records if sum(r["scores"]) / len(r["scores"]) >= 70]
print(passing_names) # ['Priya']
# the loop version names the average, which makes the condition easy to read
passing_names_loop = []
for r in records:
average = sum(r["scores"]) / len(r["scores"])
if average >= 70:
passing_names_loop.append(r["name"])
print(passing_names_loop) # ['Priya']
A concrete guideline worth keeping: reach for a comprehension when
it's one for and, at most, one simple if. The
moment you'd need a second for, a nested comprehension, or
a value you wish you could name and reuse — write the plain loop
instead. Nobody gets a readability award for cramming logic onto one
line; they get a bug report when the next person misreads it.
Go Deeper: the same one-for-one-if rule applies to dict and set comprehensions
Every readability rule in this section applies equally to the dict
and set comprehensions from Section 2 — a
{k: v for ... for ... if ... if ...} is just as hard
to read as its list-comprehension equivalent, regardless of which
container it builds.
- Nested
forclauses in a comprehension flatten a grid, read left to right in the same order as nested loops. - A comprehension inside a comprehension can build a new grid, but is already near the readability limit.
- One
forand at most one simpleifis the practical ceiling — beyond that, write the loop instead of the one-liner.
4. Lambda functions: small, anonymous, throwaway
- Lambda creates a small, unnamed function in a single line:
lambda args: expr. - A lambda can only hold one expression — no
if/elsestatements, no loops, no multiple lines. - Lambdas exist for quick, throwaway logic passed straight to another tool — not for anything you'd want to reuse by name.
lambda args: expr — args are its
parameters, and expr is the single expression it
evaluates and returns automatically. There's no return
keyword, no name, and no body beyond that one expression.
square = lambda n: n ** 2
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 4)) # 7
square and add here behave like ordinary
functions you can call — a lambda is still a real function value, it
just skips the ceremony of a full definition. Real named functions
with a proper multi-line body are Chapter 10's topic; a lambda is the
lightweight version for when the whole function fits in one
expression.
That "one expression" limit is a hard boundary, not a style
preference. A lambda cannot contain statements — no
if/else blocks, no for or
while loops, no print() followed by another
line. Anything needing more than a single expression has to be a real
function instead, once Chapter 10 introduces def.
# fine — a single expression, using the conditional expression from Chapter 4
label = lambda score: "pass" if score >= 60 else "fail"
print(label(75)) # pass
print(label(40)) # fail
# NOT allowed — a lambda can't hold statements like this:
# describe = lambda score:
# if score >= 60:
# return "pass"
# else:
# return "fail"
# SyntaxError — that's a job for a real function (Chapter 10)
n ** 2,
a + b, or a conditional expression like
"pass" if score >= 60 else "fail" all count. A statement
performs an action but doesn't hand back a value on its own —
an if block, a for loop, and an assignment
are all statements. A lambda's body must be exactly one expression.
Lambdas are almost never written standalone like square
and add above — that's just the clearest way to see the
syntax. Their real home is being handed directly to another
function, right where they're needed, which is exactly what
Section 5 covers next:
people = [("Zoe", 77), ("Priya", 91), ("Amir", 84)]
by_score = sorted(people, key=lambda person: person[1])
print(by_score)
# [('Zoe', 77), ('Amir', 84), ('Priya', 91)]
Go Deeper: why does lambda even exist, if def can do everything it does?
A full def function (Chapter 10) can do everything a
lambda can and far more — but it needs a name, a
return statement, and its own lines in the file, even
for something as small as "multiply by 2." Lambda exists for the
common case where a function is needed only once, right where
it's used, and giving it a permanent name would just add noise to
the code without adding any clarity.
lambda args: exprcreates a small, unnamed function that evaluates and returns one expression.- A lambda can't contain statements — no
if/elseblocks, no loops, only a single expression. - Lambdas are for quick, throwaway logic, usually passed straight into another function; full reusable functions with
defare Chapter 10's topic.
5. Functional tools: map(), filter(), and sorted() with key=
map(func, iterable)appliesfuncto every item and hands back the results.filter(func, iterable)keeps only the items wherefuncreturnsTrue.sorted(iterable, key=func)and.sort(key=func)sort by a computed value instead of the item itself.
map() takes a function and an iterable, and applies that
function to every item — the result has to be wrapped in
list(...) to see or use it directly, the same way
.keys() needed wrapping back in Chapter 8:
prices = [19.99, 5.00, 42.50, 3.25]
with_tax = list(map(lambda p: round(p * 1.08, 2), prices))
print(with_tax) # [21.59, 5.4, 45.9, 3.51]
map(func, iterable) applies func to every
item in iterable and returns the transformed results.
It does exactly the same job as
[func(item) for item in iterable] — a list comprehension
that just calls a function on each item.
That last sentence is worth proving directly: the comprehension
version of the same tax calculation produces the identical list,
just without needing a separate map() call and a
list(...) wrapper:
prices = [19.99, 5.00, 42.50, 3.25]
with_tax_map = list(map(lambda p: round(p * 1.08, 2), prices))
with_tax_comp = [round(p * 1.08, 2) for p in prices]
print(with_tax_map == with_tax_comp) # True — same result, either way
filter() works the same way, except the function it's
given must return True or False — only the
items where it returns True survive:
prices = [19.99, 5.00, 42.50, 3.25]
expensive = list(filter(lambda p: p > 10, prices))
print(expensive) # [19.99, 42.5]
# the equivalent comprehension:
expensive_comp = [p for p in prices if p > 10]
print(expensive_comp) # [19.99, 42.5]
filter(func, iterable) keeps only the items where
func(item) is True, dropping the rest — the
same job as [item for item in iterable if func(item)],
or more commonly just [item for item in iterable if
condition] written directly.
Most working Python developers reach for the comprehension form of
both map() and filter() in practice — it
reads left to right without the extra list(...)
wrapper. Where lambda earns its keep in this section is
sorted()'s key= argument, which has no
comprehension equivalent at all:
students = [
{"name": "Zoe", "score": 77},
{"name": "Priya", "score": 91},
{"name": "Amir", "score": 84},
]
by_score = sorted(students, key=lambda s: s["score"])
print(by_score)
# [{'name': 'Zoe', 'score': 77}, {'name': 'Amir', 'score': 84}, {'name': 'Priya', 'score': 91}]
sorted() or
.sort() calls on every item to decide the order —
instead of comparing the items themselves, Python compares whatever
the key function returns for each one. key=lambda s:
s["score"] means "sort by each record's score
field," not by the dictionaries themselves.
reverse=True flips the order without changing the key,
and .sort() is the in-place version — it reorders the
original list instead of returning a new one, the same distinction
Chapter 7's sorted() vs .sort() already
introduced for plain lists:
students = [
{"name": "Zoe", "score": 77},
{"name": "Priya", "score": 91},
{"name": "Amir", "score": 84},
]
by_score_desc = sorted(students, key=lambda s: s["score"], reverse=True)
print(by_score_desc[0]["name"]) # Priya — highest score first
students.sort(key=lambda s: s["name"]) # reorders students itself
print(students[0]["name"]) # Amir — alphabetically first
Go Deeper: sorted() works on any iterable, not just lists
sorted() accepts any iterable — a list, a set, a
dictionary's .items() — and always returns a brand-new
list, regardless of what it was given. That's different from
.sort(), which only exists on lists, since it needs
something it can reorder in place.
map(func, iterable)transforms every item;filter(func, iterable)keeps only items wherefuncreturnsTrue— both have a direct comprehension equivalent.sorted(iterable, key=func)and.sort(key=func)sort by a computed key instead of the items themselves, and have no comprehension equivalent.sorted()returns a new list;.sort()reorders the original list in place.
6. Real-world comprehensions & functional tools in production
- Cleaning a batch of records is a comprehension that transforms each one the same way.
- Filtering a dataset down to valid entries is a comprehension with an
ifcondition. - Ranking real records is
sorted()with akey=lambdacomputed from each record's fields.
sorted(..., key=lambda ...) ranks the whole collection by a computed value.
Signup forms rarely arrive clean — extra whitespace, inconsistent casing, and blank or bad fields are the norm, not the exception. A single comprehension normalizes every email in one pass, the same idea as Chapter 6's string cleanup methods, just applied to an entire batch at once:
raw_signups = [
{"email": " Priya@Example.com ", "age": "22"},
{"email": "amir@example.com", "age": "not_provided"},
{"email": "zoe@example.com ", "age": "19"},
]
cleaned_emails = [entry["email"].strip().lower() for entry in raw_signups]
print(cleaned_emails)
# ['priya@example.com', 'amir@example.com', 'zoe@example.com']
That same list has a second problem: one entry's "age"
is "not_provided", not a real number. Filtering down to
only the valid rows before doing anything else is exactly the shape
Section 1's if filter was built for:
raw_signups = [
{"email": " Priya@Example.com ", "age": "22"},
{"email": "amir@example.com", "age": "not_provided"},
{"email": "zoe@example.com ", "age": "19"},
]
valid_signups = [entry for entry in raw_signups if entry["age"].isdigit()]
print(len(valid_signups)) # 2 — the "not_provided" row is dropped
Once a dataset is clean and filtered, ranking it usually needs a
value that isn't stored directly on the record — a unit price
computed from an order's total and quantity, for example.
sorted() with a key=lambda computes that
value on the fly for every record, without ever changing the data
itself:
orders = [
{"id": "ORD-1", "amount": 42.50, "qty": 2},
{"id": "ORD-2", "amount": 64.75, "qty": 5},
{"id": "ORD-3", "amount": 10.00, "qty": 1},
]
by_unit_price = sorted(orders, key=lambda o: o["amount"] / o["qty"])
for order in by_unit_price:
unit_price = order["amount"] / order["qty"]
print(order["id"], "-", round(unit_price, 2))
# ORD-3 - 10.0
# ORD-1 - 21.25
# ORD-2 - 12.95
amount / qty, or full name from combining
first_name and last_name. Any expression
works inside key=lambda, not just a single field lookup.
Go Deeper: chaining clean → filter → rank in one pipeline
Real data-cleaning code usually chains these three steps one after another — clean, then filter, then rank — exactly in the order shown across this section. Each step stays its own clear line rather than one giant nested comprehension, which is precisely Section 3's readability guideline in action: three simple, readable lines beat one clever, unreadable one.
- A one-line comprehension cleans an entire batch of records the same way, one field transformation applied to every item.
- Filtering a dataset down to valid entries is a comprehension with an
ifcondition checking each record. sorted(records, key=lambda r: ...)ranks real records by any computed value, without altering the original data.
- Data pipelines and ETL scripts lean on comprehensions constantly — reading raw rows, cleaning each field, and filtering out bad records before anything else happens to the data.
sorted(..., key=lambda ...)powers "sort by" features in almost every real app: ranking search results by relevance, orders by date, leaderboards by score.- Lambda shows up wherever a library expects a small callback function — sort keys, filter conditions, and simple event handlers are the most common places working developers write one.
Points to Remember
- A list comprehension,
[expr for item in iterable], builds a new list in one line — the same logic as aforloop with.append(); addingif conditionfilters which items are included. - Dict comprehensions (
{k: v for ...}) and set comprehensions ({expr for ...}) apply the same idea to build dictionaries and sets, with sets automatically collapsing duplicates. - Nested comprehensions can flatten or transform a 2D grid, but readability has a ceiling — one
forand at most one simpleif; beyond that, write the plain loop instead. lambda args: exprcreates a small, unnamed function limited to a single expression — no statements, noif/elseblocks, no loops; full reusable functions withdefarrive in Chapter 10.map()andfilter()have direct comprehension equivalents;sorted(iterable, key=lambda ...)and.sort(key=lambda ...)sort by a computed value and have no comprehension equivalent.- Real-world code chains these tools together: clean a batch with a comprehension, filter it down to valid entries, then rank it with
sorted(..., key=lambda ...)— three clear steps instead of one dense one-liner.