Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple using Python program

PythonServer Side ProgrammingProgramming

When it is required to sort a list of tuples in increasing order based on last element of every tuple, a method is defined, that iterates over the tuple and performs a simple swap to achieve the same.

Below is the demonstration of the same −

Example

 Live Demo

def sort_tuple(my_tup):

   my_len = len(my_tup)
   for i in range(0, my_len):

      for j in range(0, my_len-i-1):
         if (my_tup[j][-1] > my_tup[j + 1][-1]):
            temp = my_tup[j]
            my_tup[j]= my_tup[j + 1]
            my_tup[j + 1]= temp
   return my_tup

my_tuple =[(1, 92), (34, 25), (67, 89)]
print("The tuple is :")
print(my_tuple)

print("The sorted list of tuples are : ")
print(sort_tuple(my_tuple))

Output

The tuple is :
[(1, 92), (34, 25), (67, 89)]
The sorted list of tuples are :
[(34, 25), (67, 89), (1, 92)]

Explanation

  • A method named ‘sort_tuple’ is defined, that takes a list of tuple as parameter

  • It iterates through the list, and checks to see last element of every tuple in the list of tuple is greater or not.

  • A simple swap is used to put them in their right places.

  • The list of tuple is returned as output.

  • Outside the method, a list of tuple is defined, and is displayed on the console.

  • The method is called by passing this list of tuple.

  • The output is displayed on the console.

raja
Published on 19-Apr-2021 11:08:36
Advertisements