Functional Programming Techniques

Published by Brayan K

Master functional programming patterns, pure functions, composition, and advanced FP architectures

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Functional style is about what a function touches

A functional program is built from functions that take values and return new ones, without changing anything else on the way. Python's Functional Programming HOWTO, part of its documentation, puts it this way: "Functions that have no side effects at all are called purely functional." A side effect is anything a call does besides returning its result: changing a list it was given, changing a variable outside the function, printing, writing a file.

The functional tools themselves each have a lesson of their own:

This lesson is about what makes those tools safe to combine: functions whose result depends only on their arguments, values that can't change under you, and the places where Python prefers a plain loop.

A pure function's answer depends only on its arguments

A function is pure when two things are true: its result depends only on its arguments, and calling it changes nothing the caller can see. Lists and Collections showed how the second rule breaks: a parameter is one more name for the list you pass in, so a function can change the caller's list. Here are two ways to add a bonus score:

def add_bonus(scores):
    scores.append(100)
    return scores

def with_bonus(scores):
    return scores + [100]

mine = [70, 80]
print(with_bonus(mine), mine)
print(add_bonus(mine), mine)
print(add_bonus(mine), mine)

# ✅ Expected output:
# [70, 80, 100] [70, 80]
# [70, 80, 100] [70, 80, 100]
# [70, 80, 100, 100] [70, 80, 100, 100]

with_bonus builds a new list with +, so mine stays [70, 80]. add_bonus appends to mine itself, so the same call gives a longer answer the second time: the first call changed its input. It also returns the list it changed, which is why the result and mine print the same.

A function can change its argument even when it only seems to read it. .sort() sorts a list in place, while sorted() makes a new one:

def top_two(scores):
    scores.sort(reverse=True)
    return scores[:2]

def top_two_pure(scores):
    return sorted(scores, reverse=True)[:2]

results = [55, 90, 72, 88]
print(top_two_pure(results), results)
print(top_two(results), results)

# ✅ Expected output:
# [90, 88] [55, 90, 72, 88]
# [90, 88] [90, 88, 72, 55]

Both functions return [90, 88], but only top_two reordered results. Any code that still needed the scores in their first order now has them in another.

The first rule breaks when a function reads something besides its arguments, such as a variable defined outside it:

tax_rate = 0.2

def price_with_tax(price):
    return round(price * (1 + tax_rate), 2)

print(price_with_tax(10))
tax_rate = 0.25
print(price_with_tax(10))

def price_with_rate(price, rate):
    return round(price * (1 + rate), 2)

print(price_with_rate(10, 0.2), price_with_rate(10, 0.25))

# ✅ Expected output:
# 12.0
# 12.5
# 12.0 12.5

price_with_tax(10) gave 12.0 and then 12.5. Nothing in the call changed; tax_rate did. price_with_rate takes the rate as an argument, so the call shows everything the answer depends on, and the same call always gives the same answer.

Pure describes what a caller can see, not how the function works inside. The HOWTO says a function in functional style "will still use assignments to local variables, but won't modify global variables or have other side effects". running_totals builds its list step by step, with a loop and append(), and is still pure, because that list is its own:

def running_totals(values):
    totals = []
    running = 0
    for value in values:
        running += value
        totals.append(running)
    return totals

data = [5, 3, 2]
print(running_totals(data))
print(running_totals(data))
print(data)

# ✅ Expected output:
# [5, 8, 10]
# [5, 8, 10]
# [5, 3, 2]

Two calls give the same answer, and data is untouched. itertools has accumulate() for this job. The counters in Closures & Lexical Scope in Real Projects are impure on purpose: click() returns 1, then 2, then 3, because remembering something between calls is their job.

A cache trusts the function to be pure

Decorators & Advanced Features used @functools.lru_cache(maxsize=None), which remembers each result and hands it back the next time the function is called with the same arguments, without running the function. That's only right when the same arguments always give the same answer. Here is the price function with the hidden input, cached:

import functools

tax_rate = 0.2

@functools.lru_cache(maxsize=None)
def price_with_tax(price):
    return round(price * (1 + tax_rate), 2)

print(price_with_tax(10))
tax_rate = 0.25
print(price_with_tax(10))
print(price_with_tax(20))

# ✅ Expected output:
# 12.0
# 12.0
# 25.0

The second call didn't run the function: the cache answered with the result it had from when the rate was 0.2. price_with_tax(20) hadn't been asked before, so it ran, with the new rate. A cache stores one answer for each set of arguments, so with price_with_rate(price, rate) a new rate is a new entry, and every answer stays right. functools: lru_cache, partial, reduce covers caching in full.

Pass in the clock and the dice

Some answers do depend on something outside: the time of day, a random number. Rather than read those inside the function, pass them in. A greeting that reads the clock itself gives its morning answer only in the morning, so you can't check both answers when you like. One that takes the hour as an argument can be tried with any hour:

def greeting(hour):
    return "Good morning" if hour < 12 else "Good afternoon"

print(greeting(9))
print(greeting(15))
print([greeting(h) for h in (0, 11, 12, 23)])

# ✅ Expected output:
# Good morning
# Good afternoon
# ['Good morning', 'Good morning', 'Good afternoon', 'Good afternoon']

The program still reads the clock, once, and hands the hour in. datetime.now(), from Dates & Times (datetime), gives the current date and time, and its .hour is the hour as a whole number from 0 to 23:

from datetime import datetime

print(greeting(datetime.now().hour))

What that line prints depends on when you run it, so this page shows no output for it; greeting() itself is checked above.

Randomness works the same way. Pass in the function that rolls:

def roll_two(roll):
    return roll(), roll()

def always_six():
    return 6

print(roll_two(always_six))
rolls = iter([2, 5])
print(roll_two(lambda: next(rolls)))

# ✅ Expected output:
# (6, 6)
# (2, 5)

roll_two calls whatever function it's given. always_six makes the result certain, and iter([2, 5]) with next(), from Generators & Iterators Mastery, hands out chosen values in turn. The real program passes a function that rolls a die, such as lambda: random.randint(1, 6): random.randint(1, 6) returns a whole number from 1 to 6, picked at random, and Randomness with the random Module covers it.

This is the testing advantage the HOWTO describes: "Functions don't depend on system state that needs to be replicated before running a test; instead you only have to synthesize the right input and then check that the output matches expectations." Testing with pytest: Fixtures, Parametrisation & Mocks made the same kind of stand-in with Mock(side_effect=[6, 2, 4]). Its patch() helps when you can't change a function's arguments: it swaps a name the function looks up for a Mock while the test runs. So keep the work in pure functions, and the clock, the dice and print() at the edges of the program, in as few places as you can.

Side effects inside map() run late, or never

Lambda Functions showed that map() hands out its values one at a time, when asked, and only once. That matters as soon as the mapped function does something besides returning a value. Here double() also writes to a log:

log = []

def double(n):
    log.append(n)
    return n * 2

doubled = map(double, [1, 2, 3])
print(log)
print(list(doubled))
print(log)
print(list(doubled))
print(log)

# ✅ Expected output:
# []
# [2, 4, 6]
# [1, 2, 3]
# []
# [1, 2, 3]

Creating the map didn't call double at all, so log was still empty. Reading the map with list() ran double three times, and reading it again ran it no more, because the map was used up. A side effect inside map() happens when the values are read, and as often as they're read.

print() is a side effect too, so map(print, …) prints when the map is read, not where it's written:

shown = map(print, ["a", "b"])
print("nothing printed yet")
result = list(shown)
print(result)

# ✅ Expected output:
# nothing printed yet
# a
# b
# [None, None]

The list holds the None that each print() returned: the same kind of list of Nones that Comprehensions warned about for [print(n) for n in nums]. And a map that nobody reads never runs at all. This save_all() looks as if it saves every item:

saved = []

def save_all(items):
    map(saved.append, items)
    return len(items)

def save_all_fixed(items):
    for item in items:
        saved.append(item)
    return len(items)

print(save_all(["a", "b"]), saved)
print(save_all_fixed(["a", "b"]), saved)

# ✅ Expected output:
# 2 []
# 2 ['a', 'b']

save_all() made a map object and dropped it, so saved.append was never called, and nothing said so. When the point of a call is what it does rather than what it returns, write a for loop, as save_all_fixed() does, and keep map(), filter() and comprehensions for building values. The code inside a generator waits in the same way: it runs only as the generator's values are read.

Immutable values you already know

A pure function is easier to keep pure when the values it gets can't be changed. Python's glossary defines an immutable object as "An object with a fixed value" and adds: "A new object has to be created if a different value has to be stored." Numbers, strings and tuples are immutable, and three lessons have shown what that does and doesn't protect:

Three more tools follow here: a set that can't change, a dictionary you can only read, and copies that a function keeps to itself.

frozenset: a set that can't change

Sets mentioned frozenset() in one sentence, as a set that can't change. It has every set operation that leaves the set alone: in, len(), | for a union and the rest. The methods that change a set aren't there:

tags = frozenset({"python", "fp"})
more = tags | {"code"}
print(sorted(tags), sorted(more))
tags.add("code")

# ✅ Expected output:
# ['fp', 'python'] ['code', 'fp', 'python']

# ✅ Expected error:
# AttributeError: 'frozenset' object has no attribute 'add'

tags | {"code"} built a new frozenset and left tags alone, the way + builds a new tuple. remove(), discard() and update() are missing too, each with the same kind of AttributeError. The left-hand side decides the type of a union: {"code"} | tags is a plain set. The example prints sorted(tags) rather than tags because a set has no fixed order: printed as it is, a set or frozenset of strings can come out in a different order from one run to the next.

Because a frozenset can't change, it can be a dictionary key, and two frozensets with the same members are equal in any order. That makes it the key for a pair whose order doesn't matter, such as the two players in a match:

results = {
    frozenset({"Ada", "Ben"}): "2-1",
    frozenset({"Ben", "Cleo"}): "0-3",
}
print(results[frozenset({"Ben", "Ada"})])
print(frozenset({"Cleo", "Ben"}) in results)
print({"Ada", "Ben"} == frozenset({"Ben", "Ada"}))

# ✅ Expected output:
# 2-1
# True
# True

The last line shows that a set and a frozenset with the same members are equal too. A plain set can't be the key, since it could change after it was stored: Python 3.10 to 3.13 and this site's editor stop with TypeError: unhashable type: 'set', and Python 3.14 words it TypeError: cannot use 'set' as a dict key (unhashable type: 'set').

A read-only view of a dictionary

Python 3.10 to 3.14 have no frozen dictionary among their built-in types. The standard library's types module, which gives names to some of the types Python uses itself, has MappingProxyType instead: a read-only view of a dictionary. Reading through the view works as it does on the dictionary; changing through it doesn't:

from types import MappingProxyType

settings = {"theme": "light", "size": 12}
view = MappingProxyType(settings)
print(view["size"], "theme" in view, type(view))
view["size"] = 14

# ✅ Expected output:
# 12 True <class 'mappingproxy'>

# ✅ Expected error:
# TypeError: 'mappingproxy' object does not support item assignment

del view["size"] is refused the same way, with TypeError: 'mappingproxy' object does not support item deletion, and the methods that change a dictionary, such as update(), pop() and clear(), aren't there: view.update(…) stops with AttributeError: 'mappingproxy' object has no attribute 'update'.

A view isn't a frozen copy, though. Python's documentation calls it "a dynamic view on the mapping's entries, which means that when the mapping changes, the view reflects these changes." Whoever holds the dictionary can still change it, and a list inside it can still grow:

from types import MappingProxyType

settings = {"theme": "light", "size": 12, "tags": ["a"]}
view = MappingProxyType(settings)
settings["size"] = 14
view["tags"].append("b")
print(view["size"], view["tags"])
snapshot = dict(view)
settings["size"] = 16
print(snapshot["size"], view["size"])

# ✅ Expected output:
# 14 ['a', 'b']
# 14 16

The view showed size 14 as soon as settings changed, and the list grew through the view, because the view stops changes to the dictionary's own keys and values, not to what's inside them. dict(view) made a shallow snapshot: a new dictionary whose entries do not change when the original dictionary replaces an entry. Nested mutable values, such as the list, remain shared. Code can hand out a view to prevent other code from replacing dictionary entries; it still needs a separate policy for changes inside those values.

Printed, a view looks just like a dictionary, and repr() shows what it is. For a changed version, | combines it with another dictionary into a new one, as Dictionaries did with two dictionaries:

from types import MappingProxyType

settings = {"theme": "light", "size": 12}
view = MappingProxyType(settings)
print(view)
print(repr(view))
bigger = view | {"size": 14}
print(bigger, type(bigger))
print(settings)

# ✅ Expected output:
# {'theme': 'light', 'size': 12}
# mappingproxy({'theme': 'light', 'size': 12})
# {'theme': 'light', 'size': 14} <class 'dict'>
# {'theme': 'light', 'size': 12}

bigger is a plain dictionary, and settings didn't change. view |= {"size": 14} is refused, with TypeError: '|=' is not supported by mappingproxy; use '|' instead.

Keep a copy the caller can't change

A function that stores a list it was given also keeps the caller's power to change it. make_order_shared stores the caller's list; make_order stores a tuple made from it:

def make_order(items):
    return {"items": tuple(items), "count": len(items)}

def make_order_shared(items):
    return {"items": items, "count": len(items)}

basket = ["tea", "cake"]
order = make_order(basket)
shared = make_order_shared(basket)
basket.append("jam")
print(order)
print(shared)

# ✅ Expected output:
# {'items': ('tea', 'cake'), 'count': 2}
# {'items': ['tea', 'cake', 'jam'], 'count': 2}

After basket.append("jam"), the shared order lists jam but still says its count is 2: half of it changed and half didn't. tuple(items) copied the items when the order was made. It's a shallow copy, like copy() in Lists and Collections: if an item were itself a list, the order and the basket would still share that list.

Advanced Functions & Parameters Masterclass showed that a default value is made once, when the function is defined, so a list as a default is shared by every call, and fixed that with None. An empty tuple can be the default directly, because nothing can change it:

def add_tag(tag, tags=()):
    return tags + (tag,)

print(add_tag("a"))
print(add_tag("b"))
print(add_tag("c", ("x",)))

# ✅ Expected output:
# ('a',)
# ('b',)
# ('x', 'c')

Each call builds a new tuple with +, and the default itself is still () afterwards.

An undo history from values that never change

When every change makes a new value, the old values stay as they were, and a list of them is a complete history. Here a to-do list is a tuple of (title, done) pairs. add_task and complete each return a new tuple, so every state in history is still intact:

def add_task(tasks, title):
    return tasks + ((title, False),)

def complete(tasks, title):
    return tuple((name, done or name == title) for name, done in tasks)

def show(tasks):
    if not tasks:
        return "(empty)"
    return ", ".join(name + (" (done)" if done else "") for name, done in tasks)

history = [()]
history.append(add_task(history[-1], "write tests"))
history.append(add_task(history[-1], "fix bug"))
history.append(complete(history[-1], "fix bug"))
for state in history:
    print(show(state))
print("undo:", show(history[-2]))

# ✅ Expected output:
# (empty)
# write tests
# write tests, fix bug
# write tests, fix bug (done)
# undo: write tests, fix bug

Built from one list changed in place, the history wouldn't work: every entry would be that same list, and each would show only its latest state.

Recursion doesn't replace loops in Python

Functional languages often repeat by recursion: a function handles the first item and calls itself on the rest. That works in Python for short inputs:

def total(values):
    if not values:
        return 0
    return values[0] + total(values[1:])

print(total([3, 1, 4, 1, 5]))
print(total(list(range(100))))

# ✅ Expected output:
# 14
# 4950

values[1:] is the list without its first item, and the empty list is the base case: the input the function answers without calling itself. Advanced Functions & Parameters Masterclass introduced base cases, and it also showed the limit: Python stops a recursion about a thousand calls deep. sys.getrecursionlimit() gives that limit, 1000, on Python 3.10 to 3.14 and in this site's editor. So the same function can't add up 5,000 numbers:

def total(values):
    if not values:
        return 0
    return values[0] + total(values[1:])

print(total(list(range(10))))
print(total(list(range(5000))))

# ✅ Expected output:
# 45

# ✅ Expected error:
# RecursionError: maximum recursion depth exceeded

Each call waits for the one it made, and 5,000 waiting calls is far past the limit. Some languages turn a call that's the very last step of a function, a tail call, into a jump, so it doesn't add to the depth. Here the running total is passed along, so the recursive call is the last step:

def total(values, running=0):
    if not values:
        return running
    return total(values[1:], running + values[0])

print(total(list(range(10))))
print(total(list(range(5000))))

# ✅ Expected output:
# 45

# ✅ Expected error:
# RecursionError: maximum recursion depth exceeded

Python doesn't make that jump. The notes on what's new in Python 3.14 say that "tail call optimization of Python functions" is "currently not implemented in CPython", the standard Python that these examples run on.

Both examples end with the same RecursionError line on Python 3.10 to 3.14 and in this site's editor. Other recursions can add a few words to the end of it, depending on the Python and on what the deepest call was doing.

Each call also copies the rest of the list, since values[1:] makes a new one. Counting the copied items shows the cost:

sizes = []

def total(values):
    if not values:
        return 0
    rest = values[1:]
    sizes.append(len(rest))
    return values[0] + total(rest)

print(total(list(range(100))), len(sizes), sum(sizes))

# ✅ Expected output:
# 4950 100 4950

The 100 calls that had numbers each copied the rest of the list: 99 items, then 98, and so on down to 0, which is 4,950 in all. One more call, with the empty list, stopped the recursion. For n numbers that's n × (n − 1) / 2 items, so twice as many numbers means about four times the copying. A loop has neither problem: it keeps one running total and copies nothing, and sum() does the same job in one call:

def total(values):
    running = 0
    for value in values:
        running += value
    return running

big = list(range(5000))
print(total(big), sum(big))

# ✅ Expected output:
# 12497500 12497500

Recursion still suits data that's nested a few levels deep, such as lists inside lists, which Advanced Functions & Parameters Masterclass added up with a recursive function. For a long, flat sequence, use a loop or a built-in such as sum().

Where the functional style reads worse

A few habits from functional languages read worse in Python than the plain alternative. A chain of map(), filter() and lambda is one; Lambda Functions and Comprehensions already preferred a comprehension, and here are the two side by side:

nums = [1, 2, 3, 4, 5, 6]
a = list(map(lambda n: n * n, filter(lambda n: n % 2 == 0, nums)))
b = [n * n for n in nums if n % 2 == 0]
print(a)
print(b)
print(a == b)

# ✅ Expected output:
# [4, 16, 36]
# [4, 16, 36]
# True

Same list. The comprehension reads left to right, in one place; the chain has to be read from the inside out.

Currying is another: turning a function of three arguments into a chain of one-argument functions, called as f(a)(b)(c). In Python the chain of lambdas works but is hard to read, and functools.partial, which Higher-Order Functions & Function Factories previewed, fills in an argument by name instead:

from functools import partial

def price(base, tax, discount):
    return round(base * (1 + tax) - discount, 2)

def curried_price(base):
    return lambda tax: lambda discount: price(base, tax, discount)

print(curried_price(10)(0.2)(1))
with_tax = partial(price, tax=0.2)
print(with_tax(10, discount=1), price(10, 0.2, 1))

# ✅ Expected output:
# 11.0
# 11.0 11.0

All three give 11.0. partial(price, tax=0.2) is a new function with tax already given, and you call it with the rest.

The third is reduce() for a sum or a product, where sum() and math.prod() say what they do in one word. Higher-Order Functions & Function Factories put math.prod() beside reduce(), and functools: lru_cache, partial, reduce covers reduce() for the jobs that have no built-in.

Practice: leave the team's list alone

add_score and best_two should both return a new list and leave the one they're given as it was. Fill in the two blanks; each hint line under the code holds the word for one blank, in order.

def add_score(scores, new_score):
    return ___ + [new_score]

def best_two(scores):
    return ___(scores, reverse=True)[:2]

team = [70, 95, 80]
updated = add_score(team, 88)
top = best_two(updated)
print(team)
print(updated)
print(top)

# 👉 replace ___ with scores
# 👉 replace ___ with sorted

# ✅ Expected output:
# [70, 95, 80]
# [70, 95, 80, 88]
# [95, 88]

If you reach for append() and sort() instead, team and updated both print as [95, 88, 80, 70]: they are one list, and both functions changed it.

On your own: a revenue report that leaves the orders alone

orders is a list of (item, price in pence, quantity, paid) tuples:

orders = [
    ("keyboard", 4500, 2, True),
    ("mouse", 1850, 1, False),
    ("monitor", 19900, 1, True),
    ("cable", 625, 4, True),
]

Write two pure functions. paid_lines(orders) returns a new list of (item, total) pairs for the paid orders only, largest total first, where the total is price times quantity. revenue(lines) returns the sum of the totals. Print each line with the name left-aligned in 9 characters and the amount in pounds right-aligned in 8, with two decimals, then a line for the revenue laid out the same way, and last, whether orders still equals a copy you made before calling anything.

orders = [
    ("keyboard", 4500, 2, True),
    ("mouse", 1850, 1, False),
    ("monitor", 19900, 1, True),
    ("cable", 625, 4, True),
]
before = list(orders)

def paid_lines(orders):
    lines = [(item, price * qty) for item, price, qty, paid in orders if paid]
    return sorted(lines, key=lambda line: line[1], reverse=True)

def revenue(lines):
    return sum(total for item, total in lines)

lines = paid_lines(orders)
for item, total in lines:
    print(f"{item:<9}{total / 100:>8.2f}")
print(f"{'revenue':<9}{revenue(lines) / 100:>8.2f}")
print(orders == before)

# ✅ Expected output:
# monitor    199.00
# keyboard    90.00
# cable       25.00
# revenue    314.00
# True

Practice quiz

add_bonus(scores) runs scores.append(100) and returns len(scores). With mine = [70, 80], add_bonus(mine) is called once, then print(add_bonus(mine), mine) runs. What does it print?

  • 3 [70, 80, 100]
  • 3 [70, 80]
  • 4 [70, 80, 100, 100]
  • 4 [70, 80]

Answer: 4 [70, 80, 100, 100]. Each call appends to the list it was given, which is mine itself. The first call made mine three scores long, and the second made it four.

rate = 2 and def scale(n): return n * rate. After first = scale(5) and rate = 3, what does print(first, scale(5)) print?

  • 10 10
  • 10 15
  • 15 15
  • It stops with a NameError

Answer: 10 15. scale() reads rate when it runs. first was worked out while rate was 2, and the second call sees 3: the same call gave two answers, because rate is an input the arguments don't show.

@functools.lru_cache(maxsize=None) is on def scale(n): return n * rate, with rate = 2. The program prints scale(5), sets rate = 3, then prints scale(5) and scale(6) on one line. What are the two lines?

  • 10, then 10 18
  • 10, then 15 18
  • 10, then 15 15
  • 15, then 15 18

Answer: 10, then 10 18. The cache answers scale(5) with the result of the first call, made while rate was 2. scale(6) hasn't been asked before, so it runs, with rate 3.

With log = [], double(n) runs log.append(n) and returns n * 2. After doubled = map(double, [1, 2]), what does print(len(log)) print?

  • 2
  • [2, 4]
  • It stops with a TypeError
  • 0

Answer: 0. map() calls double only when its values are read, and nothing has read them yet, so log is still empty. After list(doubled), len(log) is 2.

results = {frozenset({"Ada", "Ben"}): "2-1"}. What does print(results[frozenset({"Ben", "Ada"})]) print?

  • 2-1
  • It stops with a KeyError
  • None
  • It stops with TypeError: unhashable type: 'frozenset'

Answer: 2-1. A frozenset can be a key because it can't change, and two frozensets with the same members are equal whatever order they were written in, so the second one finds the first one's entry.

settings = {"size": 12} and view = MappingProxyType(settings). After settings["size"] = 14, what does print(view["size"]) print?

  • 12
  • It stops with TypeError: 'mappingproxy' object does not support item assignment
  • 14
  • None

Answer: 14. A MappingProxyType is a view of the dictionary, not a copy. The view refuses assignment, but the dictionary itself can still be changed, and the view shows the change.

def total(values, running=0) returns running when values is empty, and otherwise returns total(values[1:], running + values[0]). What does print(total(list(range(5000)))) do?

  • It prints 12497500
  • It prints 0
  • It stops with TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
  • It stops with RecursionError: maximum recursion depth exceeded

Answer: It stops with RecursionError: maximum recursion depth exceeded. The recursive call is the last thing the function does, but Python doesn't turn it into a loop: every call waits for the one it made, and 5,000 of them pass the limit of about 1,000.

def make_order(items): return tuple(items). With basket = ["tea"], order = make_order(basket) runs, then basket.append("jam"). What does print(order, basket) print?

  • ('tea', 'jam') ['tea', 'jam']
  • ('tea',) ['tea', 'jam']
  • ['tea'] ['tea', 'jam']
  • It stops with AttributeError: 'tuple' object has no attribute 'append'

Answer: ('tea',) ['tea', 'jam']. tuple(items) copied the items into a new tuple when make_order ran, so the later append to basket doesn't reach it. append is called on the list, which has the method.

Continue this course

Frequently asked questions

Is Python a functional language?

Not only one. Python's Functional Programming HOWTO says "Lisp, C++, and Python are multi-paradigm; you can write programs or libraries that are largely procedural, object-oriented, or functional in all of these languages." Python has functions as values, lambda, map(), comprehensions and generators, and also variables that change, loops and classes, so you choose the style that reads best for each part of a program.

How can a dictionary be a key, or go in a set?

Not as it is, since it can change. When its values are hashable, frozenset(d.items()) makes a frozenset of its (key, value) pairs, which can. With prices = {"tea": 3, "cake": 4}, a dictionary keyed by frozenset(prices.items()) found its entry again from frozenset({"cake": 4, "tea": 3}.items()), written in the other order. A list among the values makes frozenset() stop with a TypeError, as a list in a set does.

Can I raise the recursion limit instead of writing a loop?

sys.setrecursionlimit() raises it, but Python's documentation explains that the limit "prevents infinite recursion from causing an overflow of the C stack and crashing Python", and warns that "The highest possible limit is platform-dependent" and that "a too-high limit can lead to a crash." A loop has no limit to raise, so for long inputs it's the safer choice.

Why does composing thousands of functions with reduce() stop with RecursionError?

Because each composed function calls the one before it. A compose_all(*funcs) that folds the functions together with reduce(lambda f, g: lambda x: g(f(x)), funcs) gave 100 for a hundred add_one steps, and stopped with RecursionError: maximum recursion depth exceeded for 5,000 of them. The pipeline(*steps) from Higher-Order Functions & Function Factories runs its steps in a loop, and gave 5000.

Should a function return an error value instead of raising?

Some functional languages do that, with a value that holds either a result or an error. In Python a failure is an exception, which Exception Handling covers. An error value usually comes from a broad except around the call, and Exception Handling showed that except Exception hides a NameError too, so a misspelt name comes back looking like ordinary bad input.

Is side_effect in unittest.mock the same idea?

Only the same words. In Testing with pytest: Fixtures, Parametrisation & Mocks, side_effect is a setting on a Mock: what a call does instead of returning a fixed value, such as raising an error or returning the next value from a list. A side effect in this lesson is anything a function does besides returning its result.

Related lessons