Python program to Sort Tuples by their Maximum element

PythonServer Side ProgrammingProgramming

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.

raja
Published on 15-Apr-2021 13:17:41
Advertisements