We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

First-Class and Higher-Order Functions

A programming language "supports first-class functions" when functions are treated like any other variable. That means functions can be passed as arguments to other functions, can be returned by other functions, and can be assigned to variables.

  • First-class function: A function that is treated like any other value
  • Higher-order function: A function that accepts another function as an argument or returns a function

Python does support first-class and higher-order functions.

First-Class Example

from collections.abc import Callable


def square(x: int) -> int:
    return x * x


# Assign function to a variable
f: Callable[[int], int] = square

print(f(5))
# 25

Higher-Order Example

def square(x: int) -> int:
    return x * x


def my_map(func: Callable[[int], int], arg_list: list[int]) -> list[int]:
    result: list[int] = []
    for i in arg_list:
        result.append(func(i))
    return result


squares: list[int] = my_map(square, [1, 2, 3, 4, 5])
print(squares)
# [1, 4, 9, 16, 25]