Python Functions · Lesson 69 of 149

Python Lambda and Functions as Values

What you will learn

  • That a function is a value: store it, pass it, return it
  • lambda: a tiny function written as an expression
  • map, filter and reduce
  • operator helpers and functools.partial
  • Dispatch tables: a dictionary of functions
  • The late-binding trap with lambdas in loops

1. Functions are values

In Python a function is an object, like a number or a list. A def creates a function object and gives it a name. That name can be copied, stored, passed and returned:

def square(n):
    return n * n

f = square
print(f(4), f is square, f.__name__)
print(type(f).__name__, callable(f))
16 True square
function True

f = square does not call the function (no brackets): it gives the same object a second name. callable(x) says whether you can call x with brackets.

You can put functions in lists and dictionaries:

funcs = [square, abs, str.upper]
print(funcs[0](3), funcs[1](-2), funcs[2]("a"))
9 2 A

And pass them to other functions (lesson 11.2), or return them from a function:

def make_adder(n):
    def add(x):
        return x + n
    return add

add5 = make_adder(5)
print(add5(10), make_adder(1)(1))
15 2

make_adder(5) builds and returns a new function that adds 5. This is a closure (lesson 11.10): the returned function remembers n. A function that takes or returns other functions is called a higher-order function.

Quick check: what is the difference between `f = square` and `f = square(3)`?

f = square stores the function itself. f = square(3) calls it, and stores the result, 9.

2. Lambda: a function in one expression

A lambda creates a small, nameless function in one line. The form is:

lambda parameters: expression

The expression is evaluated and returned automatically: there is no return.

add = lambda a, b: a + b
print(add(2, 3))
print((lambda x: x * 2)(21))
print((lambda: 7)(), (lambda *a: sum(a))(1, 2, 3), (lambda x, y=10: x + y)(1))
5
42
7 6 11

A lambda can take any kind of parameters (defaults, *args), but its body is one expression only: no statements such as if blocks, loops, return or assignments (though a conditional expression is fine, lesson 5.4):

print((lambda x: "even" if x % 2 == 0 else "odd")(4))
even

Two facts to know:

  • A lambda's __name__ is always <lambda>, so error messages are less helpful.
  • Do not assign a lambda to a name to make a normal function. add = lambda a, b: a + b works, but a def add(a, b): return a + b is clearer and has a proper name. Style guides ask for def in that case.

Where lambdas belong

A lambda is best as a throw-away function passed straight to another function, mainly as the key of sorted, min and max (lessons 7.4 and 9.6):

words = ["banana", "kiwi", "Apple", "fig"]
print(sorted(words, key=lambda w: w.lower()))
print(sorted(words, key=lambda w: (len(w), w)))
print(max(words, key=lambda w: len(w)))

people = [("Rina", 25), ("Sam", 22), ("Lee", 31)]
print(sorted(people, key=lambda p: p[1]))
print(min(people, key=lambda p: p[1])[0])
['Apple', 'banana', 'fig', 'kiwi']
['fig', 'kiwi', 'Apple', 'banana']
banana
[('Sam', 22), ('Rina', 25), ('Lee', 31)]
Sam

When the function is longer than one simple expression, write a def and pass its name.

3. map, filter and reduce

Three classic tools take a function and a collection:

Tool What it does Returns
map(f, items) applies f to each item an iterator of the results
filter(f, items) keeps the items for which f(item) is true an iterator of those items
functools.reduce(f, items) combines the items two at a time into one value a single value
nums = [1, 2, 3, 4, 5, 6]
print(list(map(square, nums)))
print(list(map(lambda n: n * 10, nums)))
print(list(map(lambda a, b: a + b, [1, 2], [10, 20])))
print(list(filter(lambda n: n % 2 == 0, nums)))
print(list(filter(None, [0, 1, "", "a", None, [], [0]])))
[1, 4, 9, 16, 25, 36]
[10, 20, 30, 40, 50, 60]
[11, 22]
[2, 4, 6]
[1, 'a', [0]]
  • map with two lists passes one item from each (like zip).
  • filter(None, items) keeps the items that are true by themselves (lesson 5.3).
  • Both give iterators (lesson 12.4), so wrap them in list(...) to see the results.
from functools import reduce
import operator

print(reduce(lambda a, b: a + b, nums))
print(reduce(operator.mul, nums))
print(reduce(lambda a, b: a if a > b else b, nums))
print(reduce(lambda a, b: a + b, [], 0))
21
720
6
0

reduce carries a running value: ((((1+2)+3)+4)+5)+6. The third argument is a starting value, needed when the collection may be empty (without it, an empty collection is an error).

Comprehensions are usually clearer

For most uses, a comprehension says the same more readably (lesson 12.1):

print([square(n) for n in nums if n % 2 == 0])
print([n * 10 for n in nums])
[4, 16, 36]
[10, 20, 30, 40, 50, 60]

map(function_name, items) is still tidy when you already have a named function, such as map(str, nums) or map(int, text.split()).

4. The operator module

Writing lambda a, b: a + b just to add is wasteful: the operator module has a function for every operator: add, mul, sub, truediv, and more. It also has two very handy getters, used as keys:

import operator

print(operator.add(2, 3), operator.mul(4, 5))
print(sorted(people, key=operator.itemgetter(1)))
print(operator.itemgetter(0, 1)(("a", "b", "c")))
print(sorted([{"n": 2}, {"n": 1}], key=operator.itemgetter("n")))
5 20
[('Sam', 22), ('Rina', 25), ('Lee', 31)]
('a', 'b')
[{'n': 1}, {'n': 2}]
  • itemgetter(1) is the same as lambda p: p[1], and works for dictionary keys too.
  • attrgetter("x") is lambda o: o.x for the attributes of objects (chapter 13).

5. functools.partial: fixing some arguments

functools.partial(func, ...) makes a new function from an old one with some arguments already filled in:

from functools import partial

def power(base, exponent):
    return base ** exponent

square2 = partial(power, exponent=2)
cube = partial(power, exponent=3)
two_to = partial(power, 2)
print(square2(5), cube(2), two_to(10))
print(partial(int, base=2)("101"))
25 8 1024
5

two_to(10) is power(2, 10): the 2 was fixed as the first positional argument. partial(int, base=2) is a ready-made "read a binary number" function. It is a neat way to adapt a function to a place that expects fewer arguments, for example the function in map.

6. Dispatch tables

When a program must choose an action by a name or code, a dictionary of functions is cleaner than a long if / elif chain:

def calc(op, a, b):
    table = {"+": operator.add, "-": operator.sub,
             "*": operator.mul, "/": operator.truediv}
    return table[op](a, b)

print(calc("+", 6, 3), calc("-", 6, 3), calc("*", 6, 3), calc("/", 6, 3))
9 3 18 2.0

table[op] is the function, and (a, b) calls it. Adding an operation means adding one line to the dictionary. A default for unknown names uses get:

handlers = {"hello": lambda: "Hi!", "bye": lambda: "Goodbye!"}
print(handlers.get("hello", lambda: "?")())
print(handlers.get("zzz", lambda: "unknown")())
Hi!
unknown

7. Composing functions

Two functions can be joined into a new one with a function that returns a function:

def compose(f, g):
    return lambda x: f(g(x))

inc = lambda x: x + 1
dbl = lambda x: x * 2
print(compose(inc, dbl)(5))
print(compose(dbl, inc)(5))
11
12

compose(inc, dbl) doubles first (10), then adds one (11). The order matters, as the second line shows.

8. The late-binding trap

A lambda looks up the variables it uses when it runs, not when it is created. In a loop this is a famous surprise:

late = [lambda: i for i in range(3)]
print([fn() for fn in late])
[2, 2, 2]

All three lambdas share the same i, and by the time they are called, the loop has finished and i is 2. Fix it by binding the current value as a default, or with partial:

fixed = [lambda i=i: i for i in range(3)]
print([fn() for fn in fixed])

fixed2 = [partial(lambda i: i, i) for i in range(3)]
print([fn() for fn in fixed2])
[0, 1, 2]
[0, 1, 2]

lambda i=i: i gives each lambda its own default i, fixed at creation. The same trap appears with def inside loops, for example when building button callbacks. A function factory like make_multiplier(n) avoids it, because each call has its own n:

def make_multiplier(n):
    return lambda x: x * n

print([make_multiplier(k)(3) for k in range(1, 4)])
[3, 6, 9]

9. Callable objects

Anything you can call with brackets is callable: functions, lambdas, built-ins, classes, and objects whose class defines __call__ (chapter 13):

print(callable(len), callable(lambda: 1), callable("x"))

class Adder:
    def __init__(self, n):
        self.n = n

    def __call__(self, x):
        return x + self.n

a3 = Adder(3)
print(a3(4), callable(a3), list(map(a3, [1, 2])))
True True False
7 True [4, 5]

An object like a3 behaves like a function that remembers data, and can be used anywhere a function is expected.

Worked example: a small command menu

A program reads a command word and a number, and runs the right action. Each action is a function stored in a dictionary.

def run(command, n):
    actions = {
        "double": lambda x: x * 2,
        "square": lambda x: x ** 2,
        "negate": lambda x: -x,
        "half": lambda x: x / 2,
    }
    action = actions.get(command)
    if action is None:
        return f"unknown command: {command}"
    return action(n)

for cmd, n in [("double", 21), ("square", 7), ("half", 5), ("negate", 3), ("jump", 1)]:
    print(cmd, n, "->", run(cmd, n))
double 21 -> 42
square 7 -> 49
half 5 -> 2.5
negate 3 -> -3
jump 1 -> unknown command: jump
Part Why
a dictionary of lambdas one place lists every command
actions.get(command) None if the command is unknown, with no KeyError
action(n) calls whichever function was chosen

To add a command, add one line to the dictionary: no if / elif chain to extend. The commands and numbers are made up.

Common mistakes

  • Writing f(3) where you meant f (a call versus the function itself).
  • Using a lambda for something long. Use a def.
  • Assigning a lambda to a name instead of writing a def.
  • Forgetting list(...) around map or filter when you want to see the results.
  • Creating lambdas in a loop and expecting each one to keep its own loop value.
  • Forgetting the start value in reduce for a possibly empty collection.

Key takeaways

  • A function is an object: you can name it, store it in lists and dictionaries, pass it and return it.
  • lambda args: expression makes a tiny nameless function; use it for short key= functions, and a def for anything longer.
  • map, filter and reduce take a function and a collection; comprehensions are often clearer.
  • operator.itemgetter and attrgetter replace common lambdas; functools.partial fixes some arguments.
  • A dictionary of functions replaces an if / elif chain; lambdas made in loops need lambda i=i: ... to avoid late binding.

Practice

1. Sort ["pear", "fig", "banana"] by length using a lambda.

Show answer

sorted(["pear", "fig", "banana"], key=lambda w: len(w)) (or simply key=len) gives ['fig', 'pear', 'banana'].

2. What does list(map(lambda n: n + 1, [1, 2, 3])) give?

Show answer

[2, 3, 4].

3. Use filter to keep the words with more than 3 letters from ["a", "tree", "go", "house"].

Show answer

list(filter(lambda w: len(w) > 3, ["a", "tree", "go", "house"])) gives ['tree', 'house'].

4. Make square = partial(...) from power(base, exponent) so that square(5) gives 25.

Show answer

square = partial(power, exponent=2), so square(5) is 25.

5. Why does [lambda: i for i in range(3)] give three functions that all return 2?

Show answer

Each lambda looks up i when it is called, and by then the loop has finished with i = 2. Bind the value as a default: lambda i=i: i.

6. Replace an if / elif chain that picks "+", "-", "*" with a dictionary.

Show answer
import operator
table = {"+": operator.add, "-": operator.sub, "*": operator.mul}
result = table[op](a, b)