10.1. Functional Concepts#

In Chapter 9, you organized programs around objects that combine related data and behavior. Encapsulation makes changes to an object’s state explicit and controlled. Functional programming approaches the same design goal from another direction: express calculations as transformations from inputs to outputs, with fewer hidden changes to shared data. Both approaches help you organize a program so that changes are easier to understand and control.

This section builds the functional side of that partnership: purity controls effects, functions as values enable composition, and higher-order functions, closures, decorators, and comprehensions provide tools for combining behavior. Python supports these tools alongside classes, so you can use both approaches in one program. A table later in this section follows the gradebook example through four design concerns.

10.1.1. FP in Python#

Functional programming (FP) is a programming paradigm that treats computation as the evaluation of mathematical functions. Imperative programs describe how to do something step by step, often by changing program state. Functional programs instead describe what to compute by transforming inputs into outputs.

                         ┌──────────────────────┐
                         │ Programming Paradigm │
                         └──────────┬───────────┘
                  ┌─────────────────┴─────────────────┐     
                  ▼                                   ▼
          ┌───────────────┐                   ┌───────────────┐
          │  Imperative   │                   │  Declarative  │
          └───────┬───────┘                   └───────┬───────┘
          ┌───────┴───────┐                   ┌───────┴───────┐
          ▼               ▼                   ▼               ▼
┌────────────────┐ ┌────────────────┐ ┌────────────┐     ┌─────────┐
│  Procedural    │ │ Object-Oriented│ │ Functional │     │ Logic   │
└───────┬────────┘ └───────┬────────┘ └─────┬──────┘     └────┬────┘
        ▼                  ▼                ▼                 ▼
  C, Basic, Fortran     C++, Java      Haskell, Elm       Prolog, Datalog
        

Source: Kumar, “Programming Paradigms” (Kumar, n.d.).[1]

Popular Functional Programming Languages:

  • Pure: Haskell, Elm

  • Hybrid/Multi-paradigm: Scala (dual-first), Kotlin (OO-first), F# (function-first), Elixir, Clojure.

  • FP-enabled: JavaScript, Python, Rust, Swift

Key principles of functional programming:

  • Pure functions: a function always returns the same output for the same input and has no side effects (it doesn’t modify external state, perform I/O, or use randomness). For example, math.sqrt(4) is pure; random.random() is not.

  • Immutability: data is not modified in place; new values are produced instead. For example, instead of modifying a list, you produce a new one. This removes a class of bugs caused by unexpected changes to shared data. The benefits below explain what this does and does not guarantee for concurrent code.

  • First-class functions: functions are treated like any other value: they can be assigned to variables, passed as arguments, and returned from other functions.

  • Higher-order functions: functions that work with other functions by accepting them as arguments or returning them (e.g., map(), filter(), sorted()); the Higher-Order Functions section defines the term in full.

These principles answer different questions. First-class functions and higher-order functions describe how functions can be stored, passed, or returned. Purity describes what happens when a function runs. Passing a function to map(), writing a lambda, or applying a decorator does not by itself make the resulting computation pure: the functions being called may read changing state or perform side effects.

The FP ideas that have leaked into mainstream programming over the past 20 years: map/filter/reduce, lambda expressions, immutable data structures, list comprehensions, pipelines; all trace back to functional languages. Even Java and C++ have absorbed them. Understanding FP conceptually makes you better at Python even if you never write a line of Haskell, because you start to recognize when a pure function + transformation pipeline is cleaner than a loop with mutation.

Benefits of functional programming:

  • Easier testing and maintenance: Pure functions depend only on their inputs, simplifying testing.

  • Reduced side effects: By eliminating hidden state changes, debugging becomes more straightforward.

  • Easier reasoning about concurrent work: Workers can share immutable data without coordinating changes to that data. Other shared mutable state or resources can still require synchronization; immutable inputs alone do not make a whole program free of race conditions.

  • Improved modularity: Reusable components are easier to build and combine.

Drawbacks of functional programming:

  • Steep learning curve: thinking in terms of immutability, higher-order functions, and recursion instead of loops takes practice.

  • Performance concerns: Immutability can cause high memory usage due to frequent creation of new objects, which may impact performance in resource-constrained systems.

  • Recursion overhead: purely functional languages replace loops with recursion. Python limits recursion depth (about 1000 calls by default) and does not optimize tail calls, so deep recursion raises RecursionError. In Python, a loop is usually the better choice for long sequences.

The two paradigms differ in where they put the center of a program. The table summarizes the contrast. It reflects typical emphasis, not a strict boundary, since Python lets you mix both. Recursion is the classic functional way to repeat work, but Python limits recursion depth (see the drawbacks above), so in Python the practical functional tools are comprehensions and higher-order functions such as map() and filter().

Feature

Functional Programming (FP)

Object-Oriented Programming (OOP)

Core element

Pure functions

Objects and classes

State handling

Immutability: state is not modified; a new copy is returned.

Mutability: objects own and modify their internal data directly.

Programming model

Declarative: focuses on what to solve (rooted in lambda calculus, explained under Functions as Values).

Imperative: focuses on how to solve through step-by-step state changes.

Execution flow

Recursion and higher-order pipeline composition (map, filter, reduce).

Loops (for, while) and ordered method calls on objects.

Strengths

Predictable logic that is easy to test, and safer sharing of data across concurrent work.

Modeling complex real-world entities, user interfaces, and domain boundaries.

The paradigm table describes the contrast in general. A gradebook program shows how the two approaches work together: a gradebook object manages student records, while pure functions calculate averages, curve scores, and produce rankings. Its methods can call those functions and update stored records when needed. The table follows this example through four design concerns:

Design concern

OOP contribution

FP contribution

Represent students and their grades

Objects maintain related data and enforce rules.

Functions consume well-defined records.

Calculate curved grades or rankings

Methods expose these operations through an interface.

Pure functions perform calculations without changing the original grades.

Record a grade change

An explicit method updates the gradebook.

A transformation can first calculate the proposed new values.

Test the program

Check object behavior and valid state transitions.

Check calculations directly from inputs and expected outputs.

The columns describe complementary contributions. OOP methods can return new values without changing state, and functional calculations can work with objects as inputs. In the gradebook design, methods control updates while pure helpers calculate results. Separating those responsibilities lets you test a calculation without setting up the entire gradebook.

Python is not a purely functional language. It is multi-paradigm: you can write imperative code, object-oriented code, and functional-style code in the same program. In practice, Python’s functional tools are most useful when they make data transformations clearer, reduce hidden side effects, or let you reuse behavior through functions.

These ideas are not just theory. They explain directly why Python features such as comprehensions, map(), filter(), sorted(key=...), decorators, and functools are useful.

The goal is not to make Python look like a different language. The goal is to write transformations that are easy to test, easy to reason about, and hard to accidentally break with hidden shared state.

10.1.2. Purity & Immutability#

Two ideas sit at the center of functional programming. Purity means a function’s result depends only on its inputs and the function changes nothing outside itself. Immutability means creating new values instead of modifying existing ones. Together they make code easier to test and to reason about.

10.1.2.1. Pure functions#

A pure function has two properties:

  1. Deterministic: given the same inputs, it always returns the same output

  2. No side effects: it doesn’t change anything outside itself (e.g., it does not reassign a global variable, mutate an argument, print, or write to a file)

These two properties together mean you can understand a pure function in complete isolation. You don’t need to know the history of the program, what other functions have run, or what global state looks like. The function is a black box: inputs in, output out, nothing else changes. This makes pure functions:

  • Easy to test: just call the function with inputs and check the output; no setup or teardown needed

  • Easy to reason about: you can read the function body without tracking down every variable it might touch

  • Safe to reuse: calling the function twice won’t produce different results or corrupt shared state

10.1.2.2. Immutability#

Immutability means producing new values instead of modifying existing ones. For example, rather than changing a list in place, you return a new list with the change applied.

This matters because Python passes a function a reference to the same object, not a copy. When you pass a list to a function and the function calls .append() on it, the caller’s list changes too, because both names refer to one list object. This is a common source of bugs that can be hard to track down.

The fix is simple: instead of mutating, return something new. lst + [x] creates a new list. {**d, 'key': val} creates a new dictionary. The original is untouched.

Python already builds this idea into some types. Tuples, strings, and frozensets are immutable: they have no method that changes them in place, so every operation returns a new value. (1, 2) + (3,) builds a new tuple, and 'ada'.upper() returns a new string while 'ada' is unchanged. Lists, dictionaries, and sets are mutable, which is why the bugs in this section involve them. Choosing an immutable type for data that should not change makes accidental mutation impossible instead of merely unlikely.

An impure function mutates the list passed in — the caller’s list is silently changed.

def append_zero_impure(lst):
    lst.append(0)               ### modifies the input list, which is a side effect
    return lst

data = [1, 2, 3]
append_zero_impure(data)
print(data)                     ### [1, 2, 3, 0]  ← original changed, even though we didn't ask for it
[1, 2, 3, 0]

A pure function returns a new list — the original is untouched.

def append_zero_pure(lst):
    return lst + [0]

data = [1, 2, 3]
result = append_zero_pure(data)

print(data)           # [1, 2, 3] -> original data unchanged
print(result)         # [1, 2, 3, 0]
[1, 2, 3]
[1, 2, 3, 0]

The same idea applies to dictionaries. In the following example, the dictionary unpacking operator ** creates a new dictionary by copying the key-value pairs from the original. The original settings dictionary remains unchanged, and we get a new dictionary with the updated theme.

settings = {'theme': 'light', 'font_size': 12}

### {**settings, ...} copies the pairs into a new dictionary; later keys override earlier ones
updated_settings = {**settings, 'theme': 'dark', 'font_size': 14}

print(settings)         # {'theme': 'light', 'font_size': 12}   settings is unchanged
print(updated_settings) # {'theme': 'dark', 'font_size': 14}

### by contrast, these two statements change the dictionary in place, which is a side effect
prefs = {'theme': 'light', 'font_size': 12}
prefs['theme'] = 'dark'
prefs.update({'font_size': 14})
print(prefs)            # {'theme': 'dark', 'font_size': 14}   the original values are gone
{'theme': 'light', 'font_size': 12}
{'theme': 'dark', 'font_size': 14}
{'theme': 'dark', 'font_size': 14}

In the dictionary example above we see that:

  • Original State: settings is defined in memory.

  • Unpacking: {**settings, ...} copies the key-value pairs from the original dictionary into a new one.

  • Overwriting: By placing 'theme': 'dark' after the unpacking, you tell Python to use the new value if the key already exists.

  • Purity: The original settings remains untouched, preventing side effects in other parts of your program that might be relying on those original values.

Method

Modifies Original?

Good For…

{**dict, ...}

No (creates a shallow copy)

Functional programming, preserving original state.

.update()

Yes

Updating multiple keys at the same time in place.

dict[key] = value

Yes

Updating or adding a single key quickly.

Both lst + [x] and {**d, ...} make shallow copies: the new container is separate, but any nested lists or dictionaries inside it are still the same objects. Changing a nested value through the copy changes the original too. To keep the original untouched, build a new nested value as well:

config = {'name': 'demo', 'tags': ['a', 'b']}
print(config)

shallow = {**config, 'name': 'copy'}
print(shallow)
shallow['tags'].append('c')             # the inner list is shared with config
# print(config['tags'])                   # ['a', 'b', 'c']   the original changed
print(shallow)
print(config)

print()

config = {'name': 'demo', 'tags': ['a', 'b']}
pure = {**config, 'tags': config['tags'] + ['c']}   # a new inner list as well
print(pure['tags'])                     # ['a', 'b', 'c']
print(config['tags'])                   # ['a', 'b']   unchanged
{'name': 'demo', 'tags': ['a', 'b']}
{'name': 'copy', 'tags': ['a', 'b']}
{'name': 'copy', 'tags': ['a', 'b', 'c']}
{'name': 'demo', 'tags': ['a', 'b', 'c']}

['a', 'b', 'c']
['a', 'b']
### Exercise: Pure or Impure?
#   Complete the work area below `data`; leave f1 through f5 unchanged.
#   1. Replace each empty string in `answers` with 'pure' or 'impure'.
#      Classify what each function does when called with numbers (f1, f2),
#      a list of numbers (f3, f4), or a string (f5). Add a short comment
#      beside each entry explaining your choice.
#   2. Define `sorted_copy(items)` in the work area. It must return a new
#      sorted list of numbers without changing `items` or printing.
#   3. Print the result of sorted_copy(data), then print data itself.
#      Expected output: [1, 2, 3] on the first line and [3, 1, 2] on the second.
total_calls = 0

def f1(x):
    return x * 2

def f2(x):
    global total_calls
    total_calls += 1
    return x * 2

def f3(items):
    items.sort()
    return items

def f4(items):
    return sorted(items)

def f5(name):
    print(f"Hello, {name}")
    return name

data = [3, 1, 2]
### Your code starts here.
answers = {
    'f1': '',
    'f2': '',
    'f3': '',
    'f4': '',
    'f5': '',
}

# Define sorted_copy(items) here, then add the two print calls.
### Your code ends here.

Hide code cell source

### Solution
total_calls = 0

def f1(x):
    return x * 2

def f2(x):
    global total_calls
    total_calls += 1
    return x * 2

def f3(items):
    items.sort()
    return items

def f4(items):
    return sorted(items)

def f5(name):
    print(f"Hello, {name}")
    return name

data = [3, 1, 2]
### Your code starts here.
answers = {
    'f1': 'pure',       # depends only on x
    'f2': 'impure',     # changes the global total_calls
    'f3': 'impure',     # sort() changes the caller's list
    'f4': 'pure',       # sorted() returns a new list
    'f5': 'impure',     # print is output, a side effect
}

def sorted_copy(items):
    return sorted(items)

print(sorted_copy(data))    # [1, 2, 3]
print(data)                 # [3, 1, 2]   unchanged
### Your code ends here.
[1, 2, 3]
[3, 1, 2]

10.1.3. Functions as Values#

In Python, functions are first-class values; they can be assigned to variables, stored in data structures, passed as arguments, and returned from other functions.

The cell below shows each ability with an ordinary function. Notice that square without parentheses is the function itself, while square(4) calls it.

def square(x):
    return x * x

f = square                                  # assign: no parentheses, so nothing is called yet
print(f(4))                                 # 16

functions = [square, abs, str]              # store functions in a list
print([fn(-3) for fn in functions])         # [9, 3, '-3']

print(list(map(square, [1, 2, 3])))         # pass a function as an argument: [1, 4, 9]
16
[9, 3, '-3']
[1, 4, 9]

f = square copies a reference to the function, not a result, so f(4) runs square. The list holds three different functions that the loop calls in turn, and map() receives square as an argument and calls it on every item. Everything else in this chapter builds on these three abilities:

  1. Assign a function to a variable. f = square and then f(4).

  2. Store functions in a data structure. functions = [square, abs, str], which the loop calls in turn.

  3. Pass a function as an argument. map(square, [1, 2, 3]).

Lambda expressions create small anonymous functions in a single line. You first met them in 4.2 Function Design; here they become the function argument for map(), filter(), sorted(), and reduce(). They are most useful as short key functions or callback functions (a callback is a function you hand to another function to call later). A reminder of the syntax:

# Syntax: 
lambda arguments: expression

# Examples:
lambda x: x ** 2                          # one argument
lambda x, y: x + y                        # two arguments

sorted(words, key=lambda w: len(w))       # typical use: passed straight to another function

The name comes from lambda calculus, a formal system from the 1930s in which Alonzo Church expressed all computation by defining and applying anonymous functions, denoted by the Greek letter λ. It is the mathematical root of functional programming, and Python’s lambda keyword borrows its name.

A lambda is meant to be passed directly to another function. If you want a reusable function with a name, PEP 8 recommends def rather than assigning a lambda to a variable, because a def function has a real name in tracebacks and can have a docstring.

Lambdas are commonly used with map(), filter(), sorted(), and reduce(). Each of these takes a function as an argument, which makes it a higher-order function (defined in the Higher-Order Functions section below).

Function

Syntax

Description

map()

map(function, iterable)

Applies a function to every item in an iterable

filter()

filter(function, iterable)

Keeps only the items that match a condition

sorted()

sorted(iterable, key=function)

Orders items by the value the key function returns for each one

reduce()

reduce(f, seq)

Repeatedly combines items into a single value by applying a function cumulatively from left to right: f(f(f(f(1,2),3),4),5) for five items; the optional initializer is explained below

Here we see some examples of map(), filter(), and sorted() working with lambda. map() and filter() return lazy iterators, not lists, so these examples wrap them in list(...) to display the values. Choosing a Style explains lazy evaluation in detail.

# Using lambda with map(): apply a function to each item in a list
numbers = [1, 2, 3, 4, 5]
print(map(lambda x: x ** 2, numbers))

squared = list(map(lambda x: x ** 2, numbers))	### map(function, iterable)
print(squared)  # [1, 4, 9, 16, 25]             ### function applies to each element of numbers
                      ### nowadays list comprehensions are often preferred for
                      ### readability, but map with lambda can be concise for simple transformations
# Using lambda with filter(): decide which items to keep based on a condition
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))  ### filter(function, iterable) keeps only 
print(even_numbers)  # [2, 4]                               ### elements where the function returns True (even numbers in this case)     

# Using lambda with sorted(): sort a list of tuples by a specific element
students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]
sorted_by_grade = sorted(students, key=lambda student: student[1])  ### key function extracts the grade 
                                                                    ### (the second element of the tuple) for sorting
print(sorted_by_grade)  	# [('Charlie', 78), ('Alice', 85), ('Bob', 90)]
### the same as:
def get_grade(student):
    return student[1]

sorted(students, key=get_grade)   # no parentheses: passes the function itself
<map object at 0x7763f4a7a560>
[1, 4, 9, 16, 25]
[2, 4]
[('Charlie', 78), ('Alice', 85), ('Bob', 90)]
[('Charlie', 78), ('Alice', 85), ('Bob', 90)]

A key function can also return a tuple. Python compares tuples item by item, so sorted() orders the records by the first item of the key and uses the next item only to break ties. To sort a numeric field in descending order while the other fields stay ascending, negate that number in the key: a larger score becomes a smaller negative number, so it comes first.

records = [('Alice', 85, 'B'), ('Bob', 90, 'A'), ('Cara', 78, 'B'), ('Dan', 92, 'A')]

# Sort by section (index 2) ascending, then by score (index 1) descending
ranked = sorted(records, key=lambda s: (s[2], -s[1]))
print(ranked)  # [('Dan', 92, 'A'), ('Bob', 90, 'A'), ('Alice', 85, 'B'), ('Cara', 78, 'B')]
[('Dan', 92, 'A'), ('Bob', 90, 'A'), ('Alice', 85, 'B'), ('Cara', 78, 'B')]

With reduce(), you have to import reduce from functools first. When you do not pass an initial value, the accumulator starts as the first element of the iterable.

from functools import reduce

numbers = [1, 2, 3, 4, 5]

# reduce(f, seq) applies f cumulatively: f(f(f(f(1,2),3),4),5)
total = reduce(lambda acc, x: acc + x, numbers) ### acc == accumulator, x == current element
print(total)   # 15

product = reduce(lambda acc, x: acc * x, numbers)   # acc starts at 1 and multiplies each number in the list
print(product) # 120
15
120

The initializer. reduce() takes an optional third argument, the initializer: reduce(f, seq, initial). When you pass it, the accumulator starts at initial, and the function is applied to every item in the sequence, starting with the first:

reduce(f, [a, b, c], initial) computes f(f(f(initial, a), b), c)

You need an initializer in two situations:

  • The items are a different kind of value than the result. To total the grades in a list of (name, grade) tuples, the accumulator is a number but each item is a tuple. Without an initializer, the first tuple becomes the starting accumulator, and acc + s[1] then tries to add an integer to a tuple.

  • The sequence might be empty. With no items and no initializer, reduce() has nothing to return and raises TypeError. With an initializer, it returns the initializer.

from functools import reduce

students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]

### initializer 0: acc starts at 0, and every tuple is passed in as s
total = reduce(lambda acc, s: acc + s[1], students, 0)
print(total)    # 253

### without an initializer, acc starts as the first tuple ('Alice', 85)
try:
    reduce(lambda acc, s: acc + s[1], students)
except TypeError as e:
    print("TypeError:", e)

### an empty sequence returns the initializer
print(reduce(lambda acc, x: acc + x, [], 0))    # 0
253
TypeError: can only concatenate tuple (not "int") to tuple
0

Modern Python often prefers clearer built-in alternatives for common cases:

  • sum() instead of reduce() for addition

  • max() and min() instead of reduce() for extremes

  • any() and all() instead of reduce() for yes/no questions about a collection

  • a loop or a comprehension when the steps are easy to read

reduce() can be harder to read for complex logic, so reach for it only when there is genuinely no built-in equivalent. Custom accumulations are where reduce() starts to earn its place.

any() returns True if at least one item is true, and all() returns True only if every item is true. Both stop as soon as the answer is known: any() stops at the first true item, and all() stops at the first false one. They pair with map() or a comprehension that produces the true/false values:

grades = [85, 90, 78, 98]

print(sum(grades), max(grades), min(grades))        # 351 98 78

print(any([g < 80 for g in grades]))                # True: 78 is below 80
print(all([g >= 70 for g in grades]))               # True: every grade is at least 70
print(any(map(lambda g: g > 100, grades)))          # False: no grade is above 100

# The same question as a fold works, but it is longer and always visits every item
print(reduce(lambda found, g: found or g < 80, grades, False))      # True
351 98 78
True
True
False
True

The operator module. Small lambdas such as lambda s: s[1] or lambda a, b: a + b appear so often that the standard library provides them as ready-made functions in operator.

  • itemgetter(1) is the function lambda s: s[1], and itemgetter(2, 1) returns a tuple of two fields.

  • attrgetter('grade') reads an attribute from an object.

  • operator.add and operator.mul are the + and * operators as functions.

They read more clearly than the equivalent lambdas and run faster, so reach for them when the lambda only picks a field or applies one operator.

from operator import itemgetter, attrgetter, add, mul

students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]

print(sorted(students, key=itemgetter(1)))          # same as key=lambda s: s[1]
print(list(map(itemgetter(0), students)))           # ['Alice', 'Bob', 'Charlie']

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

roster = [Student('Alice', 85), Student('Bob', 90), Student('Charlie', 78)]
best = max(roster, key=attrgetter('grade'))         # same as key=lambda s: s.grade
print(best.name)                                    # Bob

numbers = [1, 2, 3, 4, 5]
print(reduce(add, numbers), reduce(mul, numbers))   # 15 120: no lambda needed
[('Charlie', 78), ('Alice', 85), ('Bob', 90)]
['Alice', 'Bob', 'Charlie']
Bob
15 120
### Exercise: reduce() and the Initializer
#   Use reduce() with an initializer for each task below.
#   1. Total the quantities in `orders`, a list of (fruit, quantity) tuples, and print the total.
#   2. Make the same call without the initializer inside try/except TypeError,
#      and print "TypeError" when it fails.
#   3. Run the call with the initializer on an empty list, `[]`, and print the result.
#   4. Build the dictionary {fruit: quantity} from `orders` with a dictionary initializer.
#      Each step must return a new dictionary, `{**acc, fruit: quantity}`, not change one in place.
#      Print the dictionary.
#   Print exactly:
#   10
#   TypeError
#   0
#   {'apple': 3, 'pear': 2, 'kiwi': 5}
from functools import reduce

orders = [('apple', 3), ('pear', 2), ('kiwi', 5)]
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
from functools import reduce

orders = [('apple', 3), ('pear', 2), ('kiwi', 5)]

# 1. The items are tuples but the result is a number, so the accumulator must start at 0.
total = reduce(lambda acc, order: acc + order[1], orders, 0)
print(total)    # 10

# 2. Without an initializer, acc starts as ('apple', 3), and acc + order[1] adds an int to a tuple.
try:
    reduce(lambda acc, order: acc + order[1], orders)
except TypeError:
    print("TypeError")

# 3. An empty sequence returns the initializer instead of raising TypeError.
print(reduce(lambda acc, order: acc + order[1], [], 0))     # 0

# 4. A dictionary initializer; each step returns a new dictionary.
stock = reduce(lambda acc, order: {**acc, order[0]: order[1]}, orders, {})
print(stock)    # {'apple': 3, 'pear': 2, 'kiwi': 5}
10
TypeError
0
{'apple': 3, 'pear': 2, 'kiwi': 5}

10.1.4. Higher-Order Functions#

A higher-order function is a function that either accepts a function as an argument or returns a function as its result. Python’s built-in higher-order functions are:

  • map(f, iter),

  • filter(f, iter),

  • sorted(iter, key=f),

  • min(iter, key=f)/max(iter, key=f), and

  • any(iter)/all(iter) .

The standard library’s functools module is specifically dedicated to higher-order functions and operations on callables, and reduce() is one of them.

Decorators are a Python idiom built entirely on this idea: a decorator is a higher-order function that takes a function and returns an enhanced version of it.

You can write your own higher-order functions:

def apply(func, x): 
    return func(x)

def square(n):
    return n **2 

print(apply(square, 7)).        ### 49

Or, with lambda:

def apply_twice(f, x):
    return f(f(x))

apply_twice(lambda x: x + 3, 10)  ### 16; we pass a lambda function as an argument

Because functions are values, a function can be stored in a variable or a dictionary and passed like any other object. In apply_twice(f, x) above, the parameter f holds a function, and f(f(x)) calls it twice.

Trace apply_twice(double, 3) with double(x) below: the first call gives double(3) = 6, and the second gives double(6) = 12.

Pass the function itself, as in apply_twice(double, 3). If you write apply_twice(double(2), 3), you first call double(2), and the number 4 that comes back is not a function, so f(x) inside apply_twice will raise a TypeError reporting that an int object is not callable.

def double(x):
    return x * 2

def negate(x):
    return -x

operations = {'double': double, 'negate': negate}   # functions stored in a dictionary
for name, op in operations.items():
    print(name, op(7))                              # double 14, negate -7

def apply_twice(f, x):
    return f(f(x))

print(apply_twice(double, 3))                       # 12
print(apply_twice(lambda s: s + '!', 'hi'))         # hi!!
double 14
negate -7
12
hi!!

10.1.4.1. Closures#

A higher-order function can also return a function. In 4.2 Function Design, you saw that a function returned this way is a closure. The name comes from the mathematical concept of an operation being “closed” within an environment, meaning the function is packaged with its environment to form a self-contained, complete entity.

A closure remembers values from the scope where it was created. This provides a clean way to attach state to a function without relying on global variables or creating a full class.

Closures pair naturally with map(), filter(), and sorted(), because a function factory can build exactly the function argument those calls need:

def make_curve(points):
    return lambda grade: min(grade + points, 100)   ### closure over points; 
                                                    ### returns a lambda function

grades = [85, 90, 78, 98]

print(list(map(make_curve(5), grades)))     # [90, 95, 83, 100]
print(list(map(make_curve(10), grades)))    # [95, 100, 88, 100]
[90, 95, 83, 100]
[95, 100, 88, 100]

Each call to make_curve creates its own points and its own returned function, so curve5 and curve10 below do not affect each other. A function object keeps the values it remembers in __closure__, which you can inspect (an optional look under the hood). Predict what the first print shows before you run the cell.

curve5 = make_curve(5)
curve10 = make_curve(10)

print(curve5(90), curve10(90))             # 95 100
print(curve5.__closure__[0].cell_contents) # 5, value remembered from make_curve(5)
95 100
5

A closure trap (late binding). A closure trap occurs because Python looks up variables in outer scopes at execution time, not at definition time. A closure remembers the variable, not the value the variable had when the function was created. The variable is looked up when the function is called. In the next cell, three lambdas are built in a loop. The closure trap is important because it is one of the most common, silent, and frustrating bugs in Python and frequently breaks UI elements.

Now, predict the printed list before you run it. Imagine that you have 3 buttons to control separately, and they show the same behavior at the same time.

funcs = [lambda x: x * i for i in range(3)]
print([f(10) for f in funcs])           # [20, 20, 20], not [0, 10, 20]

### check
print()
for idx, f in enumerate(funcs):
    # Read the live value inside the closure cell
    captured_i = f.__closure__[0].cell_contents
    print(f"Lambda {idx} -> memory: {f} | captured 'i': {captured_i}")
[20, 20, 20]

Lambda 0 -> memory: <function <lambda> at 0x7763f4a98ea0> | captured 'i': 2
Lambda 1 -> memory: <function <lambda> at 0x7763f4a99300> | captured 'i': 2
Lambda 2 -> memory: <function <lambda> at 0x7763f4a99120> | captured 'i': 2

All three lambdas share one i. By the time they are called, the loop has finished and i is 2, so each computes x * 2. Two fixes give each function its own value. A default argument captures the value at creation time, because defaults are evaluated once, when the lambda is defined. A function factory such as make_curve does the same by giving each call its own points.

### Default arguments: early binding (evaluating the value immediately during the loop).
funcs = [lambda x, i=i: x * i for i in range(3)]        # fix 1: i=i captures the current value
print([f(10) for f in funcs])                           # [0, 10, 20]


### Factory Function: creates a new intermediate scope/closure cell 
### for every single iteration.
def make_multiplier(n):                                 # fix 2: a factory gives each function its own n
    return lambda x: x * n

funcs = [make_multiplier(i) for i in range(3)]
print([f(10) for f in funcs])                           # [0, 10, 20]
[0, 10, 20]
[0, 10, 20]

Decorators, covered next, are built on closures: the wrapper function inside a decorator is a closure that remembers the original func.

### Exercise: Closures
#   1. Write `make_tax(rate)` that returns a function. The returned function takes
#      a price and returns the price with tax added, rounded to 2 decimal places.
#      Define the returned function with `def` inside `make_tax`.
#   2. Create `tax5 = make_tax(0.05)` and `tax10 = make_tax(0.10)`.
#   3. Use map() with tax5 to add 5% tax to every price in `prices`, and print the list.
#      Expected output: [4.2, 12.6, 8.4, 21.0]
#   4. Print tax10(20.0) and then tax5(20.0) to show that each closure keeps its own rate.
#      Expected output: 22.0 and then 21.0
prices = [4.0, 12.0, 8.0, 20.0]
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
prices = [4.0, 12.0, 8.0, 20.0]

def make_tax(rate):
    def add_tax(price):
        return round(price * (1 + rate), 2)     # rate is remembered from make_tax
    return add_tax

tax5 = make_tax(0.05)
tax10 = make_tax(0.10)

print(list(map(tax5, prices)))      # [4.2, 12.6, 8.4, 21.0]
print(tax10(20.0))                  # 22.0
print(tax5(20.0))                   # 21.0, tax5 still remembers 0.05
[4.2, 12.6, 8.4, 21.0]
22.0
21.0

10.1.5. Decorators#

A decorator is a higher-order function; it takes a function as input and returns a modified version without modifying the original function . The @decorator_name syntax is Python’s shorthand for func = decorator(func), making it easy to add cross-cutting behavior (e.g., logging, timing, validation, error handling, and authentication that span across an application but not part of the core business logic) without changing the original function’s code.

How decorators work:

  1. They take a function as input

  2. Wrap it in a new function that adds behavior

  3. Return the wrapper, applied automatically with @decorator_name

The next example builds a basic decorator and applies it with @.

# Basic decorator example
import functools

def my_decorator(func):     ### the decorator takes the original function as its argument
    @functools.wraps(func)  ### copies func's name and docstring onto wrapper
    def wrapper():          ### wrapper is a closure: it remembers func
        print("Something before the function")
        result = func()     ### calls the original function and stores its result
        print("Something after the function")
        return result
    return wrapper          ### the decorator returns wrapper, which replaces say_hello

@my_decorator               ### same as say_hello = my_decorator(say_hello)
def say_hello():
    """Print a greeting."""
    print("Hello!")

say_hello()

print(say_hello.__name__, "-", say_hello.__doc__)   ### metadata kept by @wraps
Something before the function
Hello!
Something after the function
say_hello - Print a greeting.

The last line shows what @wraps(func) does. After decoration, the name say_hello refers to wrapper, so without @wraps the line would print wrapper - None. With it, wrapper carries the original name and docstring, so inspecting say_hello.__name__ or using help(say_hello) identifies the original function. This preserves metadata; it does not rename the wrapper’s executing code frame. A traceback can still show a frame named wrapper.

The decorated say_hello is impure: it prints both the wrapper’s messages and the greeting. A decorator can organize useful side effects without removing them. The wrapper is a closure because it remembers func; that describes its structure, not its purity.

The wrapper above takes no arguments, so it only works for functions that take none. To decorate any function, give the wrapper *args and **kwargs and pass them through unchanged to func, as the timer decorator below does.

# A decorator that works with any arguments
from functools import wraps
from time import perf_counter, sleep

def timer_decorator(func):
    @wraps(func)                        ### preserves func's name and docstring
    def wrapper(*args, **kwargs):       ### accepts any positional and keyword arguments
        start_time = perf_counter()
        result = func(*args, **kwargs)  ### passes them unchanged to the original function
        end_time = perf_counter()
        print(f"{func.__name__} took {end_time - start_time:.4f} seconds")
        return result
    return wrapper

@timer_decorator                        ### same as slow_add = timer_decorator(slow_add)
def slow_add(a, b, delay=0.5):
    sleep(delay)                        ### doing something
    return a + b

print(slow_add(2, 3))                   ### positional arguments reach slow_add through *args
print(slow_add(2, 3, delay=0.1))        ### keyword arguments reach it through **kwargs
slow_add took 0.5001 seconds
5
slow_add took 0.1001 seconds
5

The @ line is only shorthand. Writing the assignment yourself shows the three steps: define greet, pass it to shout, and rebind the name greet to the wrapper that comes back.

from functools import wraps

def shout(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()    # change the result on the way out
    return wrapper

def greet(name):
    return f"hello, {name}"

greet = shout(greet)            # exactly what @shout above def greet would do
print(greet("ada"))             # HELLO, ADA
print(greet.__name__)           # greet, kept by @wraps
HELLO, ADA
greet

Classify behavior, not syntax. The timer adds clock readings and printing, while shout only transforms the value returned by its wrapped function. Assuming the functions and inputs shown above, their behavior differs:

Call

Pure or impure?

Reason

apply_twice(double, 3)

Pure

double only computes from its argument, and apply_twice adds no side effects.

Decorated say_hello()

Impure

The wrapper and original function print.

Decorated slow_add(2, 3)

Impure

It waits, reads a clock, and prints a timing message, even though the returned sum stays the same.

greet("ada") after greet = shout(greet)

Pure

The original function constructs a string and the wrapper returns a new uppercase string; neither changes external state.

The print(greet("ada")) demonstration performs output in the calling code. That does not make greet impure: inspect what happens inside the function call, including any functions it calls. Conversely, returning a predictable value does not make a function pure if it also prints or changes external state.

Question. Suppose double is changed to print x before returning x * 2. Would apply_twice(double, 3) still return 12? Would it still be pure? Explain before opening the feedback.

Stacking decorators. More than one decorator can sit above a function. They are applied from the bottom up, so the decorator nearest the function wraps it first and the one above wraps that result:

@bold above @italic above def label means label = bold(italic(label)). A call therefore runs bold’s wrapper first, which calls italic’s wrapper, which calls the original.

def bold(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return f"<b>{func(*args, **kwargs)}</b>"
    return wrapper

def italic(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return f"<i>{func(*args, **kwargs)}</i>"
    return wrapper

@bold
@italic
def label(text):
    return text

print(label("hi"))              # <b><i>hi</i></b>: italic wraps first, bold wraps that
<b><i>hi</i></b>
### Exercise: Write a Decorator
#   1. Write a decorator `require_positive` that wraps a function. If any positional
#      argument is <= 0, it raises ValueError("arguments must be positive").
#      Otherwise it returns the function's result.
#      Use @wraps and accept *args and **kwargs.
#   2. Apply it with @ to `area(width, height)`, which returns width * height.
#   3. Show that area(3, 4) returns 12, and that area(-1, 4) raises the ValueError,
#      caught with try/except and printing the message.
#   4. Print area.__name__ to show that @wraps kept the original name.
#      Expected output: 12, arguments must be positive, area (one per line).
from functools import wraps

### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
from functools import wraps

def require_positive(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if any(a <= 0 for a in args):
            raise ValueError("arguments must be positive")
        return func(*args, **kwargs)
    return wrapper

@require_positive
def area(width, height):
    return width * height

print(area(3, 4))               # 12
try:
    area(-1, 4)
except ValueError as error:
    print(error)                # arguments must be positive
print(area.__name__)            # area, kept by @wraps
12
arguments must be positive
area

10.1.5.1. Built-in Decorators#

@functools.wraps, used in the decorators above, is a helper for writing custom decorators. It preserves the wrapped function’s name, docstring, and other metadata.

Review from Chapter 9. Let’s take a look at the @property decorator, which you used in 9.1 OOP Design and Methods to give read access to an internal attribute. At first glance, @property only saves typing: you read the value as an attribute, without parentheses.

class BankAccount:
    def __init__(self):
        self._balance = 100

    @property
    def balance(self):
        """Current balance in dollars (read-only)."""
        return self._balance

acct = BankAccount()
print(acct.balance)         # 100
100

The bigger idea is that it turns a method into a managed attribute, which means you can:

  • compute values dynamically

  • validate data

  • make attributes read-only

  • keep internal implementation hidden

For example, an area can be computed from the radius every time it is read:

import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def area(self):
        return math.pi * self.radius ** 2

c = Circle(5)
print(c.area)               # 78.53981633974483
c.radius = 10
print(c.area)               # 314.1592653589793, recomputed on each read
78.53981633974483
314.1592653589793

So @property does more than hide parentheses: it is a decorator that runs code each time the attribute is read.

(Enrichment: optional):

class-based decorators. A decorator can also be a class. The class’s __init__ receives the function, and __call__ runs each time the decorated name is called. This is not needed for the rest of the chapter or the assignments. The CountCalls example is impure: each call changes the instance’s count attribute and prints a message.

# Class-based decorator
class CountCalls:
    def __init__(self, func):
        self.func = func
        self.count = 0
    ### __call__ makes an instance of the class behave like a function — it's invoked whenever you call the object with ().
    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"Call #{self.count} of {self.func.__name__}")
        return self.func(*args, **kwargs)

@CountCalls     ### say_hi = CountCalls(say_hi)  
def say_hi():   ### # say_hi is now a CountCalls instance
    print("Hi there!")

say_hi()        ### triggers __call__
say_hi()
say_hi()
Call #1 of say_hi
Hi there!
Call #2 of say_hi
Hi there!
Call #3 of say_hi
Hi there!

Enrichment (optional): decorators with arguments. To configure a decorator, as in @repeat(3), add one more layer. repeat(3) is an ordinary function call that returns the real decorator, and that decorator then wraps the function. The @ line is shorthand for hello = repeat(3)(hello). Three functions are nested: the outer one receives the setting (times), the middle one receives the function being decorated, and the inner wrapper runs on each call. Like the other examples, this decorator is impure because it repeats the function’s printing.

from functools import wraps

def repeat(times):                      # layer 1: receives the setting
    def decorator(func):                # layer 2: receives the function
        @wraps(func)
        def wrapper(*args, **kwargs):   # layer 3: runs on every call
            result = None
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)                              # same as hello = repeat(3)(hello)
def hello(name):
    print(f"Hello, {name}!")

hello("Ada")                            # prints the greeting three times
Hello, Ada!
Hello, Ada!
Hello, Ada!

10.1.6. Comprehensions#

You already know the comprehension syntax: list comprehensions from 6.1 Lists, dictionary comprehensions from 7.3 Dictionary Patterns, and set comprehensions from 7.4 Sets. This section looks at comprehensions from the functional side. A comprehension is Python’s built-in syntax for the same transform and filter steps that map() and filter() perform.

Each part of a comprehension lines up with one of those functions:

Comprehension part

Functional equivalent

Effect

The expression before for

map()

Transform each item

The if clause after for

filter()

Keep only the items that pass the test

The code below writes each step both ways. Each pair prints the same result.

numbers = [1, 2, 3, 4, 5, 6]

# Transform: map() vs. the expression part
print(list(map(lambda x: x ** 2, numbers)))
print([x ** 2 for x in numbers])

# Filter: filter() vs. the if clause
print(list(filter(lambda x: x % 2 == 0, numbers)))
print([x for x in numbers if x % 2 == 0])

# Filter, then transform
print(list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers))))
print([x ** 2 for x in numbers if x % 2 == 0])
[1, 4, 9, 16, 25, 36]
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
[2, 4, 6]
[4, 16, 36]
[4, 16, 36]

The last pair shows why comprehensions are usually the Pythonic choice. The nested map(filter(...)) call reads from the inside out, and it needs two lambdas. The comprehension reads left to right, with no lambdas at all.

The position of if tells you which operation you are doing. A conditional expression (from 3.1 Conditionals) in the expression part is still a map: every item produces a result. An if clause after for is a filter: some items are dropped.

numbers = [-3, -1, 0, 2, 4]

# Map with a conditional expression: every item produces a value
print([x if x >= 0 else 0 for x in numbers])

# Filter: the negative items are dropped
print([x for x in numbers if x >= 0])
[0, 0, 0, 2, 4]
[0, 2, 4]

A comprehension is an expression: its job is to build and return a new list, set, or dictionary. Write it the way you write a pure function. Compute each item from the loop data only, with no side effects such as printing, appending to another list, or changing a variable outside the comprehension.

Do not use a comprehension only for its side effects. [print(x) for x in numbers] prints every number, but it also builds a list of None values, one per print() call, and then discards it. Writing a comprehension signals that the resulting list matters, so building one that is never used makes the code misleading. In a notebook, the unused list even appears as output: when the comprehension is the last line of a cell, the list of None values shows up below the printed numbers.

numbers = [1, 2, 3, 4, 5]
[print(x) for x in numbers]   # prints, then displays the unused list
1
2
3
4
5
[None, None, None, None, None]

Use a for loop instead when the work:

  • has side effects, such as printing, writing to a file, or updating another collection,

  • needs more than one statement per item, or

  • needs to stop early with break.

### Exercise: Rewrite as Comprehensions
#   Each expression below uses map() and filter() with lambdas.
#   1. Rewrite `discounted` as a list comprehension.
#   2. Rewrite `a_names` as a list comprehension.
#   3. Rewrite `long_upper` as a single list comprehension.
#   4. Print whether each comprehension equals the original (three lines).
#   5. Print one line per name saying whether it is a map, a filter, or both.
#   Print exactly:
#   True
#   True
#   True
#   discounted: map
#   a_names: filter
#   long_upper: both
prices = [4.5, 12.0, 7.25, 20.0, 3.0]
names = ['apple', 'avocado', 'banana', 'apricot', 'cherry']

discounted = list(map(lambda p: round(p * 0.9, 2), prices))
a_names = list(filter(lambda n: n.startswith('a'), names))
long_upper = list(map(lambda n: n.upper(), filter(lambda n: len(n) > 5, names)))

### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
prices = [4.5, 12.0, 7.25, 20.0, 3.0]
names = ['apple', 'avocado', 'banana', 'apricot', 'cherry']

discounted = list(map(lambda p: round(p * 0.9, 2), prices))
a_names = list(filter(lambda n: n.startswith('a'), names))
long_upper = list(map(lambda n: n.upper(), filter(lambda n: len(n) > 5, names)))

discounted_c = [round(p * 0.9, 2) for p in prices]                  # map: transforms every item
a_names_c = [n for n in names if n.startswith('a')]                 # filter: keeps some items unchanged
long_upper_c = [n.upper() for n in names if len(n) > 5]             # both: keeps some, transforms them

print(discounted_c == discounted)       # True
print(a_names_c == a_names)             # True
print(long_upper_c == long_upper)       # True
print("discounted: map")
print("a_names: filter")
print("long_upper: both")
True
True
True
discounted: map
a_names: filter
long_upper: both

10.1.7. Choosing a Style#

Both comprehension and map/filter approaches transform or filter sequences, but they communicate intent differently.

Situation

Prefer

Simple transformation (x * 2, s.upper())

Comprehension: reads like English

Named function already defined (str.upper, int)

map(fn, seq): no need to rewrap it in a lambda

Transforming and filtering in one pass

Comprehension: [f(x) for x in seq if cond(x)] is cleaner

Chaining several transformations

Comprehension, or named intermediate steps: nested map(filter(...)) reads inside out

Result must be lazy / memory-sensitive

map/filter: they return iterators, not lists

Readability rule of thumb: if you have to stop and re-read the lambda inside map or filter to follow it, replace it with a named function or a comprehension. About 30 characters, roughly a single comparison, is where most readers start to slow down.

# Hard to read — lambda is too complex
result = list(filter(lambda s: len(s) > 3 and s.startswith('a'), words))

# Clearer as a comprehension
result = [s for s in words if len(s) > 3 and s.startswith('a')]

Pipeline readability check: a functional pipeline of 2–3 steps is fine. For longer chains, break steps into named intermediate variables so the intent stays obvious.

Lazy versus eager. map() and filter() return iterators: nothing is computed until you consume them, and they can be consumed only once. A list comprehension builds the whole list immediately. The next cell shows the difference.

numbers = [1, 2, 3, 4]

squares = map(lambda x: x ** 2, numbers)
print(squares)              # <map object at 0x...>: nothing has been computed yet
print(list(squares))        # [1, 4, 9, 16]: consuming the iterator computes the values
print(list(squares))        # []: the iterator is already exhausted

squares_list = [x ** 2 for x in numbers]
print(squares_list)         # [1, 4, 9, 16]
print(squares_list)         # [1, 4, 9, 16]: a list can be read again
<map object at 0x7763f4ab1e40>
[1, 4, 9, 16]
[]
[1, 4, 9, 16]
[1, 4, 9, 16]

Practice. Choose a style for each task, and say why, before you open the feedback:

  1. Convert the strings in ['1', '2', '3'] to integers.

  2. Keep the names longer than three letters and make them uppercase.

  3. Add up the squares of the numbers from 1 to 1,000,000 without storing them all.

### Exercise: Sorting and Filtering with Lambda
#   Given the student records below (name, grade, year):
#   1. Use filter() with a lambda to keep students with grade >= 80.
#   2. Use sorted() with a lambda to rank passing students by grade, highest first.
#   3. Use map() with a lambda to extract just the names.
#   4. Print the final list of names.
#      Expected output: ['Charlie', 'Eve', 'Alice']
students = [
    ('Alice', 85, 'junior'), ('Bob', 72, 'senior'),
    ('Charlie', 91, 'sophomore'), ('Diana', 65, 'junior'), ('Eve', 88, 'senior')
]
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
students = [
    ('Alice', 85, 'junior'), ('Bob', 72, 'senior'),
    ('Charlie', 91, 'sophomore'), ('Diana', 65, 'junior'), ('Eve', 88, 'senior')
]
passing = list(filter(lambda s: s[1] >= 80, students))
ranked  = sorted(passing, key=lambda s: s[1], reverse=True)
names   = list(map(lambda s: s[0], ranked))
print(names)  # ['Charlie', 'Eve', 'Alice']
['Charlie', 'Eve', 'Alice']

10.1.8. Designing a Pipeline#

A pipeline passes the result of one transformation to the next. To design one, first identify what each stage receives and what it must produce. Give a stage a name when its output has a useful meaning that you can inspect or test separately.

Suppose an inventory extract contains strings in the form fruit:quantity. A quantity is either blank or a nonnegative integer written as text. Every record has a colon and a nonempty fruit name. The task is to keep fruits with at least three items and rank them by quantity, highest first. Malformed records are outside this example’s input contract; a real import would validate them or handle conversion errors explicitly.

The following loop mixes text cleanup, conversion, selection, and ranking. It is a working baseline for checking the pipeline:

raw_inventory = [' apple : 3 ', 'banana:', 'pear:0', 'orange:5']
original_inventory = raw_inventory.copy()

inventory_loop = []
for line in raw_inventory:
    fruit, _, quantity_text = line.partition(':')
    fruit = fruit.strip().title()
    quantity_text = quantity_text.strip()
    if quantity_text == '':
        continue
    quantity = int(quantity_text)
    if quantity >= 3:
        inventory_loop.append((fruit, quantity))
inventory_loop.sort(key=lambda item: item[1], reverse=True)
print(inventory_loop)
[('Orange', 5), ('Apple', 3)]

Choose boundaries where the meaning or representation of a record changes:

Stage

Input record

Output record

Reason for this boundary

Parse and normalize

' apple : 3 '

('Apple', '3')

Later stages should not repeat text cleanup.

Remove missing quantities and convert

('Apple', '3')

('Apple', 3)

Numeric operations need integers; blank quantities must be removed before conversion.

Select sufficient stock

('Apple', 3)

The same tuple, if its quantity is at least three

Selection changes which records remain, not their shape.

Rank

A list of selected tuples

The same records in descending quantity order

Ranking depends on the selected collection as a whole.

The first stage uses a pure helper because field cleanup takes several operations. line.partition(':') returns the text before the first colon, the separator itself, and the text after it. The name _ receives the separator, which this helper does not use. Strip each field separately: stripping the whole line would leave the space before the colon in ' apple : 3 '.

def parse_inventory(line):
    fruit, _, quantity_text = line.partition(':')
    return fruit.strip().title(), quantity_text.strip()

print(parse_inventory(' apple : 3 '))
print(parse_inventory('banana:'))
('Apple', '3')
('Banana', '')

Build the remaining stages from the helper’s return value. In converted, the comprehension’s if clause checks the text before the expression calls int(). This order prevents int('') from raising ValueError. Once conversion is complete, every quantity is an integer, so the next stage can compare it with 3.

Print the intermediate collections to check the design. A missing fruit in parsed points to parsing; a wrong numeric value in converted points to conversion. Named boundaries make that distinction visible without reading one deeply nested expression.

parsed_inventory = [parse_inventory(line) for line in raw_inventory]
converted_inventory = [(fruit, int(text)) for fruit, text in parsed_inventory if text != '']
stocked_inventory = [item for item in converted_inventory if item[1] >= 3]
ranked_inventory = sorted(stocked_inventory, key=lambda item: item[1], reverse=True)

print('Parsed:', parsed_inventory)
print('Converted:', converted_inventory)
print('Selected:', stocked_inventory)
print('Ranked:', ranked_inventory)
print('Same result:', ranked_inventory == inventory_loop)
print('Input unchanged:', raw_inventory == original_inventory)
Parsed: [('Apple', '3'), ('Banana', ''), ('Pear', '0'), ('Orange', '5')]
Converted: [('Apple', 3), ('Pear', 0), ('Orange', 5)]
Selected: [('Apple', 3), ('Orange', 5)]
Ranked: [('Orange', 5), ('Apple', 3)]
Same result: True
Input unchanged: True

The blank quantity survives parsing as ('Banana', '') but is removed before conversion. Pear becomes ('Pear', 0) and is removed by the stock rule. Apple and Orange remain, and ranking puts Orange first. The two final True values check different properties: agreement with the baseline on this dataset and preservation of the original input. Agreement on one dataset does not establish correctness for every allowed input.

Each helper call returns a new tuple, each comprehension builds a new list, and sorted() returns a new list. These stages leave their inputs unchanged. The named lists also use memory; keeping every intermediate list is useful for this small worked example, but a large stream may need lazy stages (developed in Chapter 11). A pipeline is worthwhile when these boundaries make the transformations easier to understand.

Practice. Answer both questions before reading the feedback:

  1. Predict what changes if the stock threshold becomes six.

  2. Explain why checking text >= 3 in the conversion stage would fail.

### Exercise: Refactor a Loop into a Pipeline
#   Each row below is `name | score | department`. The loop keeps the rows with a score from
#   0 to 100 and records the best row in each department. A blank score or a score outside
#   0-100 is invalid. Rewrite the loop as a pipeline of small pure steps:
#   1. Write `parse_row(line)` that returns (name, score_text, dept): split on '|', strip each
#      field, capitalize the name with title(), and upper-case the department.
#   2. Build `valid` with comprehensions: convert score_text to an int for rows with a score,
#      then keep rows whose score is from 0 to 100.
#   3. Build `best_pipeline` as a dictionary comprehension that maps each department in `valid`
#      to the (name, score) pair with the highest score. Hint: max(..., key=...).
#   4. Check that best_pipeline == best_loop and that raw_rows is unchanged.
raw_rows = ['  alice | 85 | cs', 'BOB | | cs', 'carol | 140 | math', 'dan | 72 | math', ' eve | 91 | cs ']

best_loop = {}
for line in raw_rows:
    name, score, dept = [part.strip() for part in line.split('|')]
    if score == '':
        continue
    score = int(score)
    if not 0 <= score <= 100:
        continue
    dept = dept.upper()
    if dept not in best_loop or score > best_loop[dept][1]:
        best_loop[dept] = (name.title(), score)
print(best_loop)        # {'CS': ('Eve', 91), 'MATH': ('Dan', 72)}

### Your code starts here.



### Your code ends here.
{'CS': ('Eve', 91), 'MATH': ('Dan', 72)}

Hide code cell source

### Solution
raw_rows = ['  alice | 85 | cs', 'BOB | | cs', 'carol | 140 | math', 'dan | 72 | math', ' eve | 91 | cs ']

best_loop = {'CS': ('Eve', 91), 'MATH': ('Dan', 72)}

def parse_row(line):
    name, score_text, dept = [part.strip() for part in line.split('|')]
    return name.title(), score_text, dept.upper()

parsed = [parse_row(line) for line in raw_rows]
converted = [(name, int(text), dept) for name, text, dept in parsed if text != '']
valid = [row for row in converted if 0 <= row[1] <= 100]
best_pipeline = {
    dept: max(((name, score) for name, score, d in valid if d == dept), key=lambda pair: pair[1])
    for dept in sorted({row[2] for row in valid})
}

print(best_pipeline)                    # {'CS': ('Eve', 91), 'MATH': ('Dan', 72)}
print(best_pipeline == best_loop)       # True
print(raw_rows)                         # unchanged
{'CS': ('Eve', 91), 'MATH': ('Dan', 72)}
True
['  alice | 85 | cs', 'BOB | | cs', 'carol | 140 | math', 'dan | 72 | math', ' eve | 91 | cs ']

10.1.9. Bridge: From Pipelines to pandas#

Optional preview. Data science libraries use the same ideas you have practiced in this chapter. In pandas, a table is a DataFrame and a column is a Series. The names differ, but the tools line up with this chapter: element-wise transformation, row-wise functions, filtering, sorting, and pipelines that return new values.

Plain Python

pandas

map(f, items)

series.map(f) applies f to every value in a column

Calling a function on a whole record

df.apply(f, axis=1) passes each row to f

filter() or an if clause

df.query('curved >= 80') keeps matching rows

sorted(items, key=...)

df.sort_values('curved')

Chained steps with named intermediate lists

A method chain: each step returns a new DataFrame

The cell below reuses the make_curve closure from the Closures section as the function passed to .map().

import pandas as pd

df = pd.DataFrame({
    'name': ['alice', 'bob', 'carol', 'dan'],
    'score': [85, 72, 91, 65],
    'section': ['A', 'B', 'A', 'B'],
})

# Series.map: like map(), one value at a time
print(df['name'].map(str.title).tolist())                # ['Alice', 'Bob', 'Carol', 'Dan']
print(df['score'].map(make_curve(5)).tolist())           # [90, 77, 96, 70]: the closure from earlier

# DataFrame.apply with axis=1: the function receives a whole row
labels = df.apply(lambda row: f"{row['name'].title()} ({row['section']})", axis=1)
print(labels.tolist())                                   # ['Alice (A)', 'Bob (B)', 'Carol (A)', 'Dan (B)']
['Alice', 'Bob', 'Carol', 'Dan']
[90, 77, 96, 70]
['Alice (A)', 'Bob (B)', 'Carol (A)', 'Dan (B)']

A method chain reads like the pipeline you designed earlier: each step takes the previous result and returns a new DataFrame, so the original is not changed. assign() adds or replaces columns (with a lambda that receives the current table), query() selects rows, and sort_values() ranks them.

top = (
    df.assign(name=lambda d: d['name'].map(str.title),
              curved=lambda d: d['score'].map(make_curve(5)))
      .query('curved >= 80')
      .sort_values('curved', ascending=False)
      [['name', 'curved']]
)
print(top)
#     name  curved
# 2  Carol      96
# 0  Alice      90

print(df['name'].tolist())      # ['alice', 'bob', 'carol', 'dan']: the original table is unchanged
    name  curved
2  Carol      96
0  Alice      90
['alice', 'bob', 'carol', 'dan']

Two cautions. .map() and .apply() call a Python function once per value or row, which is slow on large tables. When pandas offers a column operation, such as df['score'] + 5, use it instead. Use .map() and .apply() when the logic is a custom function you cannot express with column operations. Also, .apply(axis=1) passes a row to your function, so the function is pure as long as it only reads that row.

10.1.10. Footnotes#