lambda
In Python, the lambda keyword creates anonymous functions, also known as lambda functions. These functions are defined using the lambda keyword followed by a list of parameters, a colon, and an expression. Python evaluates the expression and returns the result when you call the lambda function.
Python lambda Keyword Examples
Here’s a quick example of using the lambda keyword to provide the key function and sort a dictionary by values:
>>> students = {
... "Alice": 89.5,
... "Bob": 76.0,
... "Charlie": 92.3,
... "Diana": 84.7,
... "Ethan": 88.9,
... "Fiona": 95.6,
... "George": 73.4,
... "Hannah": 81.2,
... }
>>> dict(sorted(students.items(), key=lambda item: item[1]))
{
'George': 73.4,
'Bob': 76.0,
'Hannah': 81.2,
'Diana': 84.7,
'Ethan': 88.9,
'Alice': 89.5,
'Charlie': 92.3,
'Fiona': 95.6
}
In this example, you sort the dictionary by value in ascending order. To do this, you use a lambda function that takes a two-value tuple as an argument and returns the second item, which has an index of 1.
Python lambda Keyword Use Cases
- Creating callables for operations that can be expressed in a single expression
- Combining short anonymous functions with functions like
map(),filter(), andreduce() - Performing small operations that are used only once or very locally within your code
Related Resources
Tutorial
How to Use Python Lambda Functions
In this step-by-step tutorial, you'll learn about Python lambda functions. You'll see how they compare with regular functions and how you can use them in accordance with best practices.
For additional information on related topics, take a look at the following resources:
- Python's map(): Processing Iterables Without a Loop (Tutorial)
- Python's filter(): Extract Values From Iterables (Tutorial)
- Python's reduce(): From Functional to Pythonic Style (Tutorial)
- Using Python Lambda Functions (Course)
- Python Lambda Functions (Quiz)
- Python's map() Function: Transforming Iterables (Course)
- Filtering Iterables With Python (Course)