Python program to Sort Tuples by their Maximum element



When it is required to sort the tuples based on the maximum element in it, a method is defined that uses the β€˜max’ method to return the highest element.

Next the β€˜sort’ method can be used to sort the list based on the previously defined function.

Below is a demonstration of the same βˆ’

Example

 Live Demo

def get_max_value(my_val):
   return max(my_val)

my_list = [(4, 6, 8, 1), (13, 21, 42, 56), (7, 1, 9,0), (1, 2)]

print(β€œThe list is : β€œ)
print(my_list)
my_list.sort(key = get_max_value, reverse = True)

print(β€œThe sorted tuples are : β€œ)
print(my_list)

Output

The list is :
[(4, 6, 8, 1), (13, 21, 42, 56), (7, 1, 9, 0), (1, 2)]
The sorted tuples are :
[(13, 21, 42, 56), (7, 1, 9, 0), (4, 6, 8, 1), (1, 2)]

Explanation

  • A method named β€˜get_max_value’ is defined, that uses β€˜max’ function to give the highest value.

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

  • The list is sorted based on the key of previously defined function.

  • It is displayed in reverse order.

  • This is the output that is displayed on the console.

Updated on: 2021-04-15T13:19:45+05:30

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements