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:
Python
>>> 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