Kodeclik Blog
How to sort a list of tuples in Python
Given a list of tuples, for instance tuples of US states denoting (name, area), we might desire to sort them. There are 2 ways to sort such a list of tuples in Python - either using the sorted() function or the sort() method.
Sorting a list of tuples using sorted()
Let us first create a list of tuples such as:
states = [("Alabama",52419),("Arkansas",53179),
("Vermont",9616),("California",163696)]
print(states)
The output will be:
[('Alabama', 52419), ('Arkansas', 53179),
('Vermont', 9616), ('California', 163696)]
The sorted() function is the easiest to apply on the list of tuples like so:
states = [("Alabama",52419),("Arkansas",53179),
("Vermont",9616),("California",163696)]
sorted_states = sorted(states)
print(sorted_states)
print(states)
The output will be:
[('Alabama', 52419), ('Arkansas', 53179),
('California', 163696), ('Vermont', 9616)]
[('Alabama', 52419), ('Arkansas', 53179),
('Vermont', 9616), ('California', 163696)]
Note that the locations of California and Vermont are flipped (first line of our output) but the original list is not changed (second line of the output). This is because California comes alphanumerically before Vermont.
Sorting a list of tuples by the second item using sorted()
Suppose we desire to sort the same tuples but this time by the land area. So in this case, Vermont should appear first, because it is the smallest (of the given states).
states = [("Alabama",52419),("Arkansas",53179),
("Vermont",9616),("California",163696)]
sorted_states = sorted(states, key=lambda x: x[1])
print(sorted_states)
print(states)
Note that we have passed a new argument called “key” to sorted(). The key essentially takes every element of the list (denoted by “x”) and returns the second element (via x[1]) which in our case is the area because the second element of the tuples are the areas of the given states. Thus by this parameter we are instructing the sorted() function to sort by the area. The output will be:
[('Vermont', 9616), ('Alabama', 52419),
('Arkansas', 53179), ('California', 163696)]
[('Alabama', 52419), ('Arkansas', 53179),
('Vermont', 9616), ('California', 163696)]
Note that Vermont is now first and California is last. Again the original list is unchanged.
Sorting a list of tuples in reverse using sorted()
Yet another argument that sorted() uses is the reverse flag. If it is set to True (default is False) then we wish to assign the opposite interpretation. In other words, if we add “reverse=True” to the above, we are still sorting by land area of the state but we would like the largest state first and the smallest state first. Let us try this setting:
states = [("Alabama",52419),("Arkansas",53179),
("Vermont",9616),("California",163696)]
sorted_states = sorted(states, key=lambda x: x[1], reverse=True)
print(sorted_states)
print(states)
The output is:
[('California', 163696), ('Arkansas', 53179),
('Alabama', 52419), ('Vermont', 9616)]
[('Alabama', 52419), ('Arkansas', 53179),
('Vermont', 9616), ('California', 163696)]
Note that California is first and Vermont is last, and the original list of states is unchanged.
Sorting a list of tuples using sort()
The sort() method (note that it is not a function, but a method) is very similar to sorted() but it modifies the original list. We will redo the same operations as above but using sort() in place of sorted.
Note that because it is a method, there is no need for an explicit return value as the sorting happens to the original variable. Thus in the code below we are regularly re-sorting the same array w.r.t. different conditions.
states = [("Alabama",52419),("Arkansas",53179),
("Vermont",9616),("California",163696)]
print("Sorting by names:")
states.sort()
print(states)
print("\nSorting by areas:")
states.sort(key=lambda x: x[1])
print(states)
print("\nSorting by areas, reversed:")
states.sort(key=lambda x: x[1], reverse=True)
print(states)
The output is:
Sorting by names:
[('Alabama', 52419), ('Arkansas', 53179),
('California', 163696), ('Vermont', 9616)]
Sorting by areas:
[('Vermont', 9616), ('Alabama', 52419),
('Arkansas', 53179), ('California', 163696)]
Sorting by areas, reversed:
[('California', 163696), ('Arkansas', 53179),
('Alabama', 52419), ('Vermont', 9616)]
You can verify that the answers are the same as before.
In summary, sorting a list of tuples is a very common task when working with data in Python and with sort() and sorted() you can accomplish your task every easily with just a line of code!
For closely related content, checkout our blogpost on nested lists in Python.
For more Python content, checkout the math.ceil() and math.floor() functions! Also
learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.