In this article, we are going to learn different methods to Sort a list of python tuples by the first and second element with code examples. We will use sort() and sorted() functions of python in our different techniques. So let us begin:
1. Simply sort list of tuples in ascending order
In this example, we are using the sort() method to sort a list of tuples in ascending order.
lang_listtuple= [('C#',1), ('Go',7), ('Basic',8), ('Python',60)]
print('original list of tuples =\n',lang_listtuple)
lang_listtuple.sort()
print('after sorting =\n',lang_listtuple)
Output
original list of tuples =
[('C#', 1), ('Go', 7), ('Basic', 8), ('Python', 60)]
after sorting =
[('Basic', 8), ('C#', 1), ('Go', 7), ('Python', 60)]
2, Sort list of tuples by second element
Sometimes, we have to sort a list of tuples by the second element instead of ascending order. In this example, we will sort the list of tuples by the second element of the tuple. We will use some sort() function and its key parameter to put lambda function to put sort criteria on the second element.
lang_listtuple= [('C#',1), ('Go',7), ('Basic',8), ('Python',60)]
print('original list of tuples =\n',lang_listtuple)
lang_listtuple.sort(key = lambda item:item[1])
print('after sorting by second item=\n',lang_listtuple)
Output
the original list of tuples =
[('C#', 1), ('Go', 7), ('Basic', 8), ('Python', 60)]
after sorting by the second item =
[('C#', 1), ('Go', 7), ('Basic', 8), ('Python', 60)]
3. Sort by the second element in descending order
We will enhance our lambda function with additional logic to sort in reverse.
lang_listtuple= [('C#',1), ('Go',7), ('Basic',8), ('Python',60)]
print('original list of tuples =\n',lang_listtuple)
lang_listtuple.sort(key = lambda item:item[1],reverse=True)
print('after sorting by second item descending order =\n',lang_listtuple)
p
Output
the original list of tuples =
[('C#', 1), ('Go', 7), ('Basic', 8), ('Python', 60)]
after sorting by second item descending order =
[('Python', 60), ('Basic', 8), ('Go', 7), ('C#', 1)]
4. sorted() function to sort by second element
In this example we will use sorted() function to sort the list of tuples. We will use the lambda expression also to sort on second element.
lang_listtuple= [('C#',1), ('Go',7), ('Basic',8), ('Python',60)]
print('original list of tuples = \n',lang_listtuple)
sorted(lang_listtuple,key = lambda item:item[1])
print('sorted list of tuple by second=\n',lang_listtuple)
Output
original list of tuples =
[('C#', 1), ('Go', 7), ('Basic', 8), ('Python', 60)]
sorted list of a tuple by second=
[('C#', 1), ('Go', 7), ('Basic', 8), ('Python', 60)]