Use Lambda with the sorted() Function
One of the most common use cases for lambda functions is to serve as a quick, inline function for higher-order functions (functions that take other functions as arguments). A prime example is Python's built-in sorted() function, which can accept a key argument. The key specifies a function to be called on each element before making sorting comparisons.
Imagine you have a list of tuples, where each tuple represents a product and its price. You want to sort this list based on the price.
Open the file ~/project/lambda_sorted.py in the editor. Add the following code:
## A list of tuples (product, price)
products = [('Laptop', 1200), ('Mouse', 25), ('Keyboard', 75)]
## Sort the list by price (the second element of each tuple) using a lambda function
sorted_products = sorted(products, key=lambda item: item[1])
## Print the sorted list
print(sorted_products)
In this code, key=lambda item: item[1] tells sorted() to use the second element (item[1], which is the price) of each tuple as the value for sorting. This is much more concise than defining a separate function with def.
Save the file and run it from the terminal:
python3 ~/project/lambda_sorted.py
You will see the list of products sorted by price in ascending order.
[('Mouse', 25), ('Keyboard', 75), ('Laptop', 1200)]
This pattern is extremely common and useful for sorting complex data structures in a simple and readable way.