Skip to main content

Functional Programming in Python

Lambda Functions

0:00
LearnStep 1/3

Anonymous Functions in Action

In Python, lambda functions are small, anonymous functions defined with the lambda keyword. Unlike functions defined with def, lambdas are expressions, meaning they yield a function object directly. They are restricted to a single expression; they cannot contain statements or annotations.

Syntax

The syntax is lambda arguments: expression. The expression is evaluated and returned. They are most idiomatic when used as throwaway functions for callbacks or key functions.

python

Common Use Cases

Lambdas shine when passed as arguments to higher-order functions like sorted(), map(), and filter().

python

Readability Limits

While concise, lambdas can hurt readability if they become complex. Python's style guide (PEP 8) discourages assigning lambdas to variables (use def instead). If a lambda expression barely fits on one line, it should probably be a named function.

The Operator Module

For simple operations like retrieving an item or attribute, the operator module is often faster and more readable than a lambda.

python