In Python, we can use the lambda function to simplify sorting operations. lambda is a small anonymous function that quickly defines functions based on the provided expression. When sorting, we typically combine lambda with the sorted() function or the sort() method of a list to specify the sorting key.
Example 1: Sorting a List Using sorted() and lambda
Assume we have an integer list, and we want to sort it based on the absolute value of the numbers.
pythonnumbers = [-5, -2, 0, 1, 3, 4] sorted_numbers = sorted(numbers, key=lambda x: abs(x)) print(sorted_numbers)
The output will be:
shell[0, 1, -2, 3, 4, -5]
Here, lambda x: abs(x) defines an anonymous function that takes x as input and returns the absolute value of x. This returned value is used as the sorting key.
Example 2: Sorting a List of Tuples Using sort() and lambda
Assume we have a list containing student names and scores, and we want to sort the student information based on scores in descending order.
pythonstudents = [('Alice', 88), ('Bob', 70), ('Dave', 92), ('Carol', 78)] students.sort(key=lambda student: student[1], reverse=True) print(students)
The output will be:
shell[('Dave', 92), ('Alice', 88), ('Carol', 78), ('Bob', 70)]
In this example, lambda student: student[1] creates a function that takes a student tuple (e.g., ('Alice', 88)) and returns its score (e.g., 88). Setting reverse=True sorts the list in descending order based on scores.
Example 3: Combining lambda with Other Functions
We can also incorporate other functions within lambda, such as the lower() method for strings, to achieve case-insensitive string sorting.
pythonnames = ['alice', 'Bob', 'dave', 'Carol'] names.sort(key=lambda name: name.lower()) print(names)
The output will be:
shell['alice', 'Bob', 'Carol', 'dave']
Here, lambda name: name.lower() ensures that sorting ignores the case of the strings.
Through these examples, we can see that using lambda for sorting is both flexible and powerful. It enables us to define complex sorting logic with minimal code.