🐍 Python for Everyone

← Back to all chapters

Chapter 9 of 27 Beginner 35 min read

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

Building a new list, dictionary, or set by looping over an existing one is one of the most common things real Python code does — cleaning a batch of form input, pulling out just the valid rows, computing a price with tax applied to every item. A comprehension writes that entire loop in a single line. Paired with lambda for small one-off logic, this is the syntax that makes everyday Python code read the way experienced developers actually write it.
Sub-topic 1 of 6

1. List comprehensions

At a glance
  • 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 condition at the end filters out items you don't want.
Use this when: you already know you'd write a for loop that does nothing but build a new list.
What is... a list comprehension? A list comprehension is a single-line way to build a new list from an existing one: [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.
loop_vs_comprehension.py
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 vs. comprehension version, side by side
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:

filtering_with_if.py
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:

filtering_as_a_loop.py
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]
try_list_comprehensions.py
Click "Run Code" — try changing the condition to len(word) <= 4.
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.

Quick recap
  • A list comprehension, [expr for item in iterable], builds a new list in one line — the same logic as a for loop with .append().
  • Adding if condition at the end filters which items make it into the new list.
  • A comprehension never modifies the original iterable — it always returns a new list.
Sub-topic 2 of 6

2. Dict & set comprehensions

At a glance
  • 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.
Default habit: if the result needs named lookups, build a dict comprehension; if it just needs uniqueness, build a set comprehension.

A dict comprehension follows the same shape as a list comprehension, just with a key: value pair in front instead of a single expression:

dict_comprehension.py
names = ["Priya", "Amir", "Zoe"]

name_lengths = {name: len(name) for name in names}
print(name_lengths)   # {'Priya': 5, 'Amir': 4, 'Zoe': 3}
What is... a dict comprehension? A dict comprehension, {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:

transforming_a_dict.py
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:

set_comprehension.py
words = ["the", "cat", "sat", "on", "the", "mat"]

unique_lengths = {len(word) for word in words}
print(unique_lengths)   # {2, 3} — duplicates collapse automatically
What is... a set comprehension? A set comprehension, {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:

normalizing_emails.py
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
try_dict_set_comprehensions.py
Click "Run Code" — try adding an if condition to only keep temps above 16°C.
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.

Quick recap
  • 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.
Sub-topic 3 of 6

3. Nested comprehensions & readability limits

At a glance
  • A comprehension can loop over a nested list (a 2D grid), the same way nested for loops do.
  • Every extra for or if you add makes a comprehension harder to read, not easier.
  • Readability beats cleverness — a comprehension that needs explaining should just be a loop.
Rule of thumb: one 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:

flattening_a_grid.py
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]
What is... a nested comprehension? A nested comprehension is a comprehension with more than one 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:

transforming_a_grid.py
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:

too_clever_vs_a_loop.py
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']
What is... "too clever"? "Too clever" means code that's technically correct but takes more effort to read than to just rewrite plainly. A comprehension crosses that line the moment you have to pause and mentally unpack it before trusting what it does — at that point, the extra lines a loop costs are worth paying for the time everyone saves reading it later.

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.

try_nested_comprehensions.py
Click "Run Code" — try adding a row to seating and re-running.
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.

Quick recap
  • Nested for clauses 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 for and at most one simple if is the practical ceiling — beyond that, write the loop instead of the one-liner.
Sub-topic 4 of 6

4. Lambda functions: small, anonymous, throwaway

At a glance
  • Lambda creates a small, unnamed function in a single line: lambda args: expr.
  • A lambda can only hold one expression — no if/else statements, 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.
Use this when: you need a tiny piece of logic for one call, and naming it would be more ceremony than it's worth.
What is... a lambda? A lambda is a small, anonymous function written as 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.
basic_lambda.py
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.

what_fits_in_a_lambda.py
# 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)
What is... an expression, versus a statement? An expression produces a single value — 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:

lambda_as_an_argument.py
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)]
try_lambda.py
Click "Run Code" — try writing your own one-line lambda below it.
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.

Quick recap
  • lambda args: expr creates a small, unnamed function that evaluates and returns one expression.
  • A lambda can't contain statements — no if/else blocks, no loops, only a single expression.
  • Lambdas are for quick, throwaway logic, usually passed straight into another function; full reusable functions with def are Chapter 10's topic.
Sub-topic 5 of 6

5. Functional tools: map(), filter(), and sorted() with key=

At a glance
  • map(func, iterable) applies func to every item and hands back the results.
  • filter(func, iterable) keeps only the items where func returns True.
  • sorted(iterable, key=func) and .sort(key=func) sort by a computed value instead of the item itself.
Use this when: you're about to write a comprehension anyway and want to see the alternative most real codebases mix in.

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:

using_map.py
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]
What is... map()? 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:

map_vs_comprehension.py
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:

using_filter.py
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]
What is... filter()? 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:

sorting_with_a_key.py
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}]
What is... a sort key? A sort key is a function that 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:

reverse_and_in_place.py
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
try_functional_tools.py
Click "Run Code" — try sorting by_price with reverse=True.
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.

Quick recap
  • map(func, iterable) transforms every item; filter(func, iterable) keeps only items where func returns True — 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.
Sub-topic 6 of 6

6. Real-world comprehensions & functional tools in production

At a glance
  • 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 if condition.
  • Ranking real records is sorted() with a key=lambda computed from each record's fields.
Pattern to remember: comprehensions clean and filter one item at a time; 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:

cleaning_a_batch.py
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:

filtering_valid_entries.py
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:

ranking_by_computed_key.py
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
What is... a computed key? A computed key is a value derived from a record's fields, rather than a field stored directly — unit price from amount / qty, or full name from combining first_name and last_name. Any expression works inside key=lambda, not just a single field lookup.
try_bringing_together.py
Click "Run Code" — try filtering to only verified reviews too.
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.

Quick recap
  • 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 if condition checking each record.
  • sorted(records, key=lambda r: ...) ranks real records by any computed value, without altering the original data.
In the Real World

Points to Remember

← All Chapters Take the Quiz →