Skip to content
Python for Quantitative Finance / Built-In Data Structures

Functions as Objects and Higher-Order Functions

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 map function, including its multi-argument form, to apply a function across one or more sequences in parallel;
  • write and use a lambda expression, and judge when a lambda improves readability versus when a named function would be clearer.

In this lesson

  1. Functions as first-class objects
  2. map: a built-in, more general apply_to_each
  3. lambda: anonymous functions

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.