Python program to sort a list of tuples by second Item



Python program to sort a list of tuples by second Item

Given a list of tuples, write a Python program to sort the tuples by the second item of each tuple.

Examples:

Input : [('for', 24), ('Python', 8), ('Pandas', 30)] 
Output : [('Python', 8), ('for', 24), ('Pandas', 30)]

Input : [('452', 10), ('256', 5), ('100', 20), ('135', 15)]
Output : [('256', 5), ('452', 10), ('135', 15), ('100', 20)]

Method #1: Using the Bubble Sort

# Python program to sort a list of tuples by the second Item
 
# Function to sort the list of tuples by its second item
def Sort_Tuple(tup): 
     
    # getting length of list of tuples
    lst = len(tup) 
    for i in range(0, lst): 
         
        for j in range(0, lst-i-1): 
            if (tup[j][1] > tup[j + 1][1]): 
                temp = tup[j] 
                tup[j]= tup[j + 1
                tup[j + 1]= temp 
    return tup 
 
# Driver Code 
tup =[('for', 24), ('is', 10), ('Geeks', 28), 
      ('Geeksforgeeks', 5), ('portal', 20), ('a', 15)] 
       
print(Sort_Tuple(tup)) 

Output:

 

 

[('Geeksforgeeks', 5), ('is', 10), ('a', 15), ('portal', 20), ('for', 24), ('Geeks', 28)]

 

Method #2: Using sort() method

# Python program to sort a list of
# tuples by the second Item using sort() 
 
# Function to sort hte list by second item of tuple
def Sort_Tuple(tup): 
 
    # reverse = None (Sorts in Ascending order) 
    # key is set to sort using second element of 
    # sublist lambda has been used 
    tup.sort(key = lambda x: x[1]) 
    return tup 
 
# Driver Code 
tup = [('rishav', 10), ('akash', 5), ('ram', 20), ('gaurav', 15)] 
 
# printing the sorted list of tuples
print(Sort_Tuple(tup)) 

Output:

[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]

Method #3: Using sorted() method

# Python program to sort a list of
# tuples by the second Item using sorted() 
 
# Function to sort the list by second item of tuple
def Sort_Tuple(tup): 
 
    # reverse = None (Sorts in Ascending order) 
    # key is set to sort using second element of 
    # sublist lambda has been used 
    return(sorted(tup, key = lambda x: x[1]))  
 
# Driver Code 
tup = [('rishav', 10), ('akash', 5), ('ram', 20), ('gaurav', 15)] 
 
# printing the sorted list of tuples
print(Sort_Tuple(tup)) 

Output:

[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]

Last Updated on October 3, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs