Python sort list of tuples | descending, first, second, last, multiple elements, value, alphabetically

Python sort list of tuples using the 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 the list of tuples by first and second elements by using indexes or values.

• tup to sort on first tuple element
• tup to sort on second and so on.

1. Example sort by the First element value

my_data = [('P', 1), ('M', 3), ('A', 2), ('B', 4)]

my_data.sort(key=lambda tup:tup)

print(my_data)

Output:

[(‘P’, 1), (‘A’, 2), (‘M’, 3), (‘B’, 4)]

2. Example sort by the Second element value

my_data = [('P', 1), ('M', 3), ('A', 2), ('B', 4)]

my_data.sort(key=lambda tup:tup)

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:

[('peter',1), ('mary',5), ('anthony',6), ('brandon',4)]

And wanted to sort this list and get something like:

[('anthony', 6), ('brandon', 4), ('mary', 5), ('peter', 1)]

Answer: You can do it using a sort() or sorted() functions.

sorted() function

my_data = [('peter', 1), ('mary', 5), ('anthony', 6), ('brandon', 4)]

sorted_data = sorted(my_data)

print(sorted_data)

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 sorting the list of tuples first by descending order and alphabetically in python 3.

lst is a list of tuples with each tuple holding the value in the format (value, key). And you want to sort it based on the key which is at the index 0 of the tuple. In that case, you should be calling the .sort() with keys as:

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

lst = [(12, 'tall', 'blue', 1), (2, 'short', 'red', 9),
(4, 'tall', 'blue', 13)]
s = sorted(lst, key=lambda x: (x, x))
print(s)

Output:

How to sort the list of tuples by the 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 the argument which specifies what to sort the list on.

tuple1 = [(1, 3), (3, 2), (2, 1)]

ntuple = sorted(tuple1, key=lambda x: x[-1])
print(ntuple)

Output: [(2, 1), (3, 2), (1, 3)]