Introduction
In Python a function is a value, just like a number or a list. You can store it in a variable, put it in a list or dictionary, and pass it to another function.
Once you see a function as a value, new designs become possible. You can hand a function to sorted to say how to compare items, or choose which function to run by looking it up, and a lot of repetitive code disappears.
How it works
A function in a variable
def shout(text):
return text.upper() + "!"
speak = shout
print(speak("hello"))speak = shout does not call anything; there are no brackets. It gives the same function a second name, and the objects panel shows both shout and speak pointing to one function box. speak("hello") then calls it.
lambda, map and filter
square = lambda x: x * x
print(square(7))
nums = [3, 8, 1, 6]
print(list(map(lambda n: n * 10, nums)))
print(list(filter(lambda n: n > 4, nums)))A lambda is a one-line function without a name: lambda x: x * x takes x and returns x * x.
map(f, items)appliesfto every item.filter(f, items)keeps the items wherefreturns True.
Both are lazy, so list(...) turns the result into a list you can print. A list comprehension often says the same thing more clearly.
Syntax
f = len # no brackets: the function itself
square = lambda x: x * x
list(map(square, [1, 2, 3]))
sorted(names, key=len)
Example
ops = {
"add": lambda a, b: a + b,
"mul": lambda a, b: a * b,
}
print(ops["add"](3, 4))
print(ops["mul"](3, 4))Looking up a function by name, then calling it, replaces a long chain of if/elif. Adding a new operation is one new line in the dictionary.
Line by line
opsis a dictionary whose values are functions.ops["add"]looks up a function, but does not call it yet.(3, 4)straight after it makes the call, so the result is 7.- The second
printdoes the same with"mul", giving 12.
Expected result
7
12
In the real world
Sorting by a chosen key, responding to a button and handling each web address are all done by passing or looking up functions. In web frameworks, a table of paths and functions is the main structure of an application.
Common mistakes
- Calling instead of passing:
sorted(names, key=len())is an error; passkey=len, without brackets. - Long lambdas. If it needs more than one short expression, write a normal
def. - Forgetting that
mapandfiltergive results only once; convert to a list if you need them again.
Best practices
- Use a lambda only for short, simple expressions.
- Write a normal
defwhen the logic needs a name or more than one step. - Prefer a comprehension when it says the same thing more clearly.
Summary
Functions are values that can be stored and passed. A lambda is a short anonymous function. map and filter apply a function across items, and a dictionary can choose which function to run.
Practice
Build a dictionary with "min", "max" and "sum" mapped to the built-in functions, then apply each one to [4, 9, 2].
Quick check
Key takeaways
- Without brackets a function is a value, and with brackets it is a call.
- A lambda holds a single expression.
- A dictionary of functions replaces long if chains.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.