Python sort list of tuples using sort method needed key which sorts lists in place. And also offers a convenient way to sort tuples based on the index of tuple elements.
You can sort list of tuples by first and second element by using index or values.
tup[0]
to sort on first tuple elementtup[1]
to sort on second and so on.
1. Example sort by the First element value
1 2 3 4 5 |
my_data = [('P', 1), ('M', 3), ('A', 2), ('B', 4)] my_data.sort(key=lambda tup:tup[1]) print(my_data) |
Output:
[(‘P’, 1), (‘A’, 2), (‘M’, 3), (‘B’, 4)]
2. Example sort by the Second element value
1 2 3 4 5 |
my_data = [('P', 1), ('M', 3), ('A', 2), ('B', 4)] my_data.sort(key=lambda tup:tup[0]) print(my_data) |
Output:
[(‘A’, 2), (‘B’, 4), (‘M’, 3), (‘P’, 1)]
How to sort a list of tuples by the first element alphabetically in python?
You have a list of tuples like this:
1 |
[('peter',1), ('mary',5), ('anthony',6), ('brandon',4)] |
And wanted to sort this list and get something like:
1 |
[('anthony', 6), ('brandon', 4), ('mary', 5), ('peter', 1)] |
Answer: You can do it using a sort() or sorted() functions.
1 2 3 4 5 |
my_data = [('peter', 1), ('mary', 5), ('anthony', 6), ('brandon', 4)] sorted_data = sorted(my_data) print(sorted_data) |
1 2 3 4 5 |
my_data = [('peter', 1), ('mary', 5), ('anthony', 6), ('brandon', 4)] my_data.sort() print(my_data) |
Python sort list of tuples descending
Here is an example of the sorting the list of tuples first by the descending order and alphabetically in python 3.
lst
is a list of tuple with each tuple holding the value in the format (value, key) . And you want to sort it based on the key which is at index 0
of the tuple. In that case you should be calling the .sort()
with key as:
1 2 3 4 5 |
from operator import itemgetter lst = [('C', 1), ('A', 5), ('B', 6), ('D', 4)] lst.sort(key=itemgetter(0)) print(lst) |
Output: [(‘A’, 5), (‘B’, 6), (‘C’, 1), (‘D’, 4)]
Python sort list of tuples by multiple elements
1 2 3 4 |
lst = [(12, 'tall', 'blue', 1), (2, 'short', 'red', 9), (4, 'tall', 'blue', 13)] s = sorted(lst, key=lambda x: (x[2], x[3])) print(s) |
Output:

How to sort list of tuples by last element in python?
Answer: Specify the key
argument in the sorted
function.
The sorted
function (as well as the list.sort
method) has an optional key
argument which specifies what to sort the list on.
1 2 3 4 |
tuple1 = [(1, 3), (3, 2), (2, 1)] ntuple = sorted(tuple1, key=lambda x: x[-1]) print(ntuple) |
Output: [(2, 1), (3, 2), (1, 3)]
Do comment if you have any doubts on this tutorial.
Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.