In Python, you can use the sorted() function or .sort() method to sort iterables. A lambda function is often used as a key to define custom sorting logic, making it easier to sort data based on specific criteria.
Let’s say you have a list of dictionaries, and you want to sort it by a specific key (e.g., “age”).
data = [ {'name': 'John', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 22} ] # Sort by 'age' using lambda function sorted_data = sorted(data, key=lambda x: x['age']) print(sorted_data);
OutPut:-
[{'name': 'Bob', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Alice', 'age': 30}]
lambda x: x[‘age’] is used to extract the ‘age’ value from each dictionary to determine the sorting order.The key argument specifies the function used to extract the sorting key from each element in the iterable.
You can also use a lambda function to sort by multiple criteria. For example, you might want to sort a list of tuples first by age and then by name.
data = [ ('John', 25), ('Alice', 30), ('Bob', 22), ('Charlie', 25) ] # Sort by age first, then by name sorted_data = sorted(data, key=lambda x: (x[1], x[0])) print(sorted_data);
Output:-
[('Bob', 22), ('John', 25), ('Charlie', 25), ('Alice', 30)]
Here, the lambda function returns a tuple (x[1], x[0]), which means the list is sorted by the second element (age) first, and if ages are the same, it sorts by the first element (name).
If you want to sort in descending order, you can use the reverse=True parameter.
data = [5, 3, 8, 1, 2] # Sort in descending order sorted_data = sorted(data, key=lambda x: x, reverse=True) print(sorted_data);
Output:-
[8, 5, 3, 2, 1]
In this example, reverse=True ensures that the list is sorted in descending order.
However, you might encounter issues when trying to use lambda incorrectly. Take below example:
a = sorted(a, lambda x: x.modified, reverse=True)
The error encountering in above code :
This error occurs because sorted() expects the key parameter to be a function that accepts one argument, but the lambda function here isn’t correctly used.
Issue: The sorted() function’s key parameter expects a function that takes one argument and returns a value that is used to compare the elements of the iterable.
In your case, the lambda x: x.modified should be passed as the key argument, but the syntax is incorrect.
Fix: To resolve the issue, you should pass the lambda function correctly as the key argument to sorted(). Here’s the corrected code:
a = sorted(a, key=lambda x: x.modified, reverse=True)
Explanation: key=lambda x: x.modified tells Python to use the modified attribute of each element in the list a as the sorting criterion.