Python sort list of tuples by the first and second element

Tuple Python

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:

# Using Sort() function

In this example we are using sort method to sort a list of tuples.

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)]

# Sort by second element

In this example we will sort on second element of tuple. We will use same sort() function and we will pass a lambda function to put sort criteria on 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)]

# 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)]

# 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)]