How to sort a list of tuples in python?

Consider a list of tuples list_1 = [('A', 3), ('C', 2), ('B', 1)]. The list_1 when sorted by 1st item in tuple gives output as [('A', 3), ('B', 1), ('C', 2)]. list_1 when sorted by 2nd element in tuple gives output as [('B', 1), ('C', 2), ('A', 3)]. list_1.sort() by default sorts the list of tuples by 1st item in tuple.

When we try to sort a list of tuples according to a specific position, all the data items at that particular position should be of the same data type. In list_1 for each tuple, the second data item is a numeric value. If the data items are different, it will raise a TypeError exception.

This article discusses different approaches to sort a list of tuples by any custom value.

Sort a list of tuples by using the sort() function

Python supports the inbuilt sort() function to sort the list. sort() function sorts the list in ascending order by default. The sort() function doesn't take any arguments and doesn't return anything. The two optional parameters for the sort() function are key and reverse.

The syntax for the sort() function is as follows.

#syntax:
list.sort(key = ..., reverse =...)
  • The parameter reverse takes a boolean value. If the reverse is set to True it sorts the list in descending order.
  • The parameter key takes a function as a value for user-defined comparison.

To sort the list by the 2nd element in the tuple, we pass a user-defined function as a value to the key parameter.

Consider the list list_1 = [('A', 3), ('C', 2), ('B', 1)]. list_1.sort(key = lambda x : x[1]) sorts the list_1 by second element in tuple. lambda is an anonymous function that can take any number of arguments but has one expression. The lambda function in the below code receives each tuple as an argument and returns second element of the tuple.

list_1 = [('A', 3), ('C', 2), ('B', 1)]
print("list_1: ", list_1)
list_1.sort(key = lambda x : x[1])
print("The sorted list_1: ", list_1)

The above code return output as

list_1:  [('A', 3), ('C', 2), ('B', 1)]
The sorted list_1:  [('B', 1), ('C', 2), ('A', 3)]

Instead of using the lambda function, we can also use itemgetter(n). itemgetter(n) assumes a sequence(list,tuple,string) as an input and returns nth element. Thus, list_1.sort(key = itemgetter(1)) will sort the list of tuples by 2nd element.

Sort a list of tuples by using the sorted() function

sorted() function is a built-in function in python that takes three arguments list, key(optional), reverse(optional). The major difference between the sort() and sorted() function is, sorted() function returns a sorted list and doesn't modify the original list.

The syntax for the sorted() function is as follows.

#syntax:
sorted(list, key=..., reverse=...)
  • The parameter reverse takes a boolean value. If the reverse is set to True it sorts the list in descending order.
  • The parameter key takes a function as a value for user-defined comparison.

Consider the list list_1 = [('A', 3), ('C', 2), ('B', 1)]. sorted(list_1, key = lambda x : x[1]) takes list_1 as parameter and sorts the list of tuples by 2nd element. The sorted list is assigned to variable list_2.

list_1 = [('A', 3), ('C', 2), ('B', 1)]
print("list_1: ", list_1)
list_2 = sorted(list_1, key = lambda x : x[1])
print("The sorted list_2: ", list_2)

Output

list_1:  [('A', 3), ('C', 2), ('B', 1)]
The sorted list_2:  [('B', 1), ('C', 2), ('A', 3)]

Sort a list of tuples by using for loop

Consider the list list_1 = [('A', 3), ('C', 2), ('B', 1)]. To sort the list by the 2nd element of the tuple, two loops are used. The for loop compares the second element of the tuple in each pass, if they are not in ascending order, tuples are swapped.

list_1 = [('A', 3), ('C', 2), ('B', 1)]
print("list_1: ", list_1)
for i in range(len(list_1)):
    for j in range(i+1, len(list_1)):
            if list_1[i][1] > list_1[j][1]:
               list_1[i], list_1[j] =list_1[j], list_1[i]
print("list_1: ", list_1)

Output

list_1:  [('A', 3), ('C', 2), ('B', 1)]
list_1:  [('B', 1), ('C', 2), ('A', 3)]
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions