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



When it is required sort a list of tuples in the increasing order, based on the last element of every tuple in the list of tuple, methods are defined to first sort the list of tuple based on last element, and another method to sort based on previous method.

Below is a demonstration of the same −

Example

 Live Demo

def sort_last_elem(num):
   return num[-1]

def sort_structure(my_tuple):
   return sorted(my_tuple, key=sort_last_elem)

my_list = [(45, 31), (23, 67), (92, 60), (90, 12)]
print("The list is :")
print(my_list)
print("The sorted list of elements is :")
print(sort_structure(my_list))

Output

The list is :
[(45, 31), (23, 67), (92, 60), (90, 12)]
The sorted list of elements is :
[(90, 12), (45, 31), (92, 60), (23, 67)]

Explanation

  • A method named ‘sort_last_elem’ is defined that sorts the list based on the last element.

  • Another method named ‘sort_structure’ is defined that returns the sorted list, based on the key which is the previously defined function.

  • A list of tuple is defined, and is displayed on the console.

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

  • It is displayed as the output on the console.


Advertisements