
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Tuples by Their Maximum Element in Python
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.
Advertisements