Skip to content
Related Articles

Related Articles

Improve Article
Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
  • Difficulty Level : Basic
  • Last Updated : 26 Nov, 2020

The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple.

Input: [(1, 3), (3, 2), (2, 1)]
Output: [(2, 1), (3, 2), (1, 3)]
Explanation: sort tuple based on the last digit of each tuple.

Methods #1: Using sorted().

Sorted() method sorts a list and always returns a list with the elements in a sorted manner, without modifying the original sequence.

Approach:

  • Take a list of tuples from the user.
  • Define a function that returns the last element of each tuple in the list of tuples.
  • Define another function with the previous function as the key and sort the list.
  • Print the sorted list.

Python3






def last(n):
    return n[-1]  
   
def sort(tuples):
    return sorted(tuples, key=last)
   
a=[(1, 3), (3, 2), (2, 1)]
print("Sorted:")
print(sort(a))

Output:

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

Methods #2: Using Bubble Sort.

Access the last element of each tuple using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e. O(n^2).

Python3




# 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 =[(1, 3), (3, 2), (2, 1)]
          
print(Sort_Tuple(tup))

Output:

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

Methods #3: Using sort().

The sort() method sorts the elements of a given list in a specific ascending or descending order.

Python3




# 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 = [(1, 3), (3, 2), (2, 1)]
    
# printing the sorted list of tuples 
print(Sort_Tuple(tup))  

Output:

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :