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.
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
Write the lambda keyword followed by your comma-separated parameter names.
- 2
Place a colon, followed by the single expression you want to evaluate and return.
- 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.
# 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)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.
Python Functions
Master Python functions. Learn how to write reusable code using def, define arguments, return values, and understand scope locally and globally.
Python Math Module Functions
Quick reference guide for the Python math standard library. Learn how to use trigonometric, logarithmic, rounding, and arithmetic functions.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.