Python: Sort List Of Tuples By First Element In 10 Seconds

How do you sort a list of tuples by the first element in each tuple in Python?

To sort a list of tuples in Python use the .sort() list method if you want to modify the list to sort or the sorted() function if you want to generate a new list.

Use the parameter key with either function and set the value of that parameter to a lambda expression that returns the required tuple you want to sort by.

For example, here is a list of tuples using the .sort() list method:

>>> my_list = [(10, 1), (5, 100), (3, 10)]
>>> my_list.sort(key=lambda x: x[0])
>>> print(my_list)
[(3, 10), (5, 100), (10, 1)]

As you can see from the above code the .sort() list method mutates the original my_list variable by sorting all the tuples in order according to their first element .

Notice also the sorting is done in ascending order. If you need to change the order to be descending then, as these are numbers, insert a negative sign in the lambda function for the element being referenced.

Here’s an example sorting a list of tuples in descending order using the first element of each tuple:

>>> my_list = [(10, 1), (5, 100), (3, 10)]
>>> my_list.sort(key=lambda x: -x[0])
>>> print(my_list)
[(10, 1), (5, 100), (3, 10)]

As you can see from the results of this code the first element in each tuple is now in descending order.

Sort By Second Element?

What if you need to sort by each tuple’s second element, instead of the first?

This is simply changed by editing the reference value in the lambda function. Currently in the lambda function the value x represents each tuple in the list and x[0] references the first value in the tuple.

To sort by the second element simply change the reference from x[0] to x[1] .

Here’s an example demonstrating the change:

>>> my_list = [(10, 1), (5, 100), (3, 10)]
>>> my_list.sort(key=lambda x: x[1])
>>> print(my_list)
[(10, 1), (3, 10), (5, 100)]

As you can see from the above code the order of the tuples in the list is now set in order according to the second element in each tuple.

Summary

Sorting a list of tuples in Python by their first element is an easy task that can easily be accomplished using the .sort() list method or the sorted() function with the key parameter set to a lambda function: lambda x: x[0] .

Photo of author
Ryan Sheehy
Ryan has been dabbling in code since the late '90s when he cut his teeth exploring VBA in Excel. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP.