Every function so far has been called, never passed around. This note reveals that in Python, functions are first-class objects, exactly like an
int or a list: they have a type, they can be assigned to a variable, stored in a list, and — most usefully — passed as an argument to another function. A function that takes another function as an argument (or returns one) is called a higher-order function, and this style of programming is what makes map, and the pattern behind it, so compact and reusable. This note also introduces lambda, Python's syntax for a small, unnamed function written inline.Learning objectives. By the end of this note you should be able to:
- explain what it means for functions to be "first-class objects" in Python, and give an example of a function stored in a variable or a list;
- write a higher-order function that accepts another function as a parameter and applies it to elements of a sequence;
- use the built-in
mapfunction, including its multi-argument form, to apply a function across one or more sequences in parallel; - write and use a
lambdaexpression, and judge when alambdaimproves readability versus when a named function would be clearer.
In this lesson
- Functions as first-class objects
map: a built-in, more generalapply_to_eachlambda: anonymous functions
Before you start
The full lesson, with worked examples and exercise solutions, is for members.
Read the full lessonNew to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.