lambda | Python Keywords – Real Python

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:

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(), and reduce()
  • Performing small operations that are used only once or very locally within your code

How to Use Python lambda Functions

For additional information on related topics, take a look at the following resources: