How to Lambda Sort a List

Published on Aug. 22, 2023, 12:15 p.m.

To sort a list using a lambda function in Python

To sort a list using a lambda function in Python, you can use the sorted() function or the list.sort() method and pass in a lambda function as the key argument that determines the sorting order based on the values of the elements in the list.

Here’s an example of how to sort a list of tuples based on the second element of each tuple:

my_list = [('999', '9'), ('343', '34'), ('303', '30')]
sorted_list = sorted(my_list, key=lambda x: x[1])

print(sorted_list)

In this example, the lambda function takes a single argument x, which represents a tuple from the list, and returns the value of the second element of the tuple using x[1]. The sorted() function sorts the list my_list based on the values of the second element in each tuple using the lambda function as the key, and assigns the sorted list to sorted_list.

The resulting sorted_list is [('999', '9'), ('303', '30'), ('343', '34')], which is sorted based on the second element in each tuple.

You can use a similar approach to sort a list based on any arbitrary property or value of the elements in the list.

To sort a list in Python

To sort a list in Python, you can use the sorted() function or the list.sort() method. The sorted() function returns a new sorted list, while the list.sort() method sorts the list in place.

Here’s an example of how to use the sorted() function to sort a list of integers in ascending order:

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list = sorted(my_list)
print(sorted_list)

In this example, the sorted() function takes the list my_list as an argument and returns a new sorted list that is assigned to sorted_list. The resulting sorted_list is [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9], which is sorted in ascending order.

Here’s an example of how to use the list.sort() method to sort the same list in place:

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
my_list.sort()
print(my_list)

In this example, the list.sort() method is called on my_list, which sorts the list in place. The resulting my_list is [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9], which is sorted in ascending order.

You can also pass a reverse=True argument to either the sorted() function or the list.sort() method to sort the list in descending order.

Tags: