How to Use Lambda Functions in Python (Anonymous Functions)

Learn how to use lambda functions in Python. Master anonymous functions, inline callbacks, and sorting list data with lambda keys.

Try Code in Editor

Explanation

In Python, functions are first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and returned from functions. While standard functions are declared using the `def` keyword, Python also provides a shorthand syntax for creating anonymous inline functions: `lambda` functions.

A lambda function is defined with the `lambda` keyword, followed by a list of arguments, a colon, and a single expression. The syntax is `lambda arguments: expression`. Unlike `def` functions, lambdas do not require a `return` statement; the result of the expression is returned automatically. They are limited to a single logical line, making them ideal for simple, one-off operations.

Lambda functions are most commonly used as arguments to higher-order functions like `sorted()`, `map()`, and `filter()`. For example, you can pass a lambda function to `sorted()`'s `key` argument to define custom sorting criteria, or use them as lightweight callback functions inside graphical or event-driven applications.

Step-by-Step Implementation

  1. 1

    Write the lambda keyword followed by your comma-separated parameter names.

  2. 2

    Place a colon, followed by the single expression you want to evaluate and return.

  3. 3

    Pass the lambda directly as a callback to functions like sorted(), map(), or filter().

Code Example

This script demonstrates constructing lightweight anonymous functions using lambda.

lambda_functions.py
Try in Editor
# 1. Simple lambda function assigned to a variable
double = lambda x: x * 2
print("Double of 5:", double(5))

# 2. Multi-argument lambda
add = lambda x, y: x + y
print("Sum of 3 + 4:", add(3, 4))

# 3. Using lambda as a sorting key (sorting by age)
people = [
    {"name": "Alice", "age": 28},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 35}
]
people.sort(key=lambda person: person["age"])
print("Sorted by age:", people)
Terminal Output
Double of 5: 10
Sum of 3 + 4: 7
Sorted by age: [{'name': 'Bob', 'age': 22}, {'name': 'Alice', 'age': 28}, {'name': 'Charlie', 'age': 35}]

Frequently Asked Questions

Can a lambda function contain loops or multiple statements?

No, lambda functions in Python are strictly limited to a single expression. If you need complex logic, loops, or variable assignments, you must define a standard function using def.

Should I assign lambda functions to variables?

Generally no. PEP 8 guidelines suggest using a standard def statement instead of assigning a lambda to a variable, as standard functions provide better stack trace names.

Related How-To Guides

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.