
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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.
- Related Articles
- Python program to sort tuples by frequency of their absolute difference
- Python – Sort by Maximum digit in Element
- Python - Sort Matrix by Maximum Row element
- Python program to sort tuples in increasing order by any key.
- Python program to sort a list of tuples by second Item
- Python – Sort Tuples by Total digits
- Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
- Sort Tuples in Increasing Order by any key in Python program
- Sort Tuples by Total digits in Python
- Python program to sort a list of tuples alphabetically
- Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple using Python program
- Python program to sort a tuple by its float element
- Sort list of tuples by specific ordering in Python
- Python Program to sort rows of a matrix by custom element count
- Python – Sort Matrix by Maximum String Length

Advertisements