- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Sort Tuples by Total digits
When it is required to sort tuples by total digits, a method is defined that converts every element in the list to a string, and gets the length of each of these strings, and adds them up. This is displayed as result of the method.
Below is a demonstration of the same −
def count_tuple_digits(row): return sum([len(str(element)) for element in row]) my_tuple = [(32, 14, 65, 723), (13, 26), (12345,), (137, 234, 314)] print("The tuple is :") print(my_tuple) my_tuple.sort(key = count_tuple_digits) print("The result is :") print(my_tuple)
The tuple is : [(32, 14, 65, 723), (13, 26), (12345,), (137, 234, 314)] The result is : [(13, 26), (12345,), (32, 14, 65, 723), (137, 234, 314)]
A method named ‘count_tuple_digits’ is defined that takes tuple as a parameter, and converts every element in the list to a string, and gets the length of each of these strings, and adds them up.
This is done using ‘sum’ method which is returned as output.
A list of tuple is defined and displayed on the console.
The tuple is sorted by specifying the key as the method.
This is the output that is displayed on the console.
- Sort Tuples by Total digits in Python
- Python – Sort Matrix by total characters
- Python program to Sort Tuples by their Maximum element
- Sort list of tuples by specific ordering in Python
- Python program to sort tuples in increasing order by any key.
- Sort Tuples in Increasing Order by any key in Python program
- Python program to sort a list of tuples by second Item
- Python program to sort tuples by frequency of their absolute difference
- Convert list of tuples into digits in Python
- Python – Trim tuples by K
- Trim tuples by N elements in Python
- Python program to sort a list of tuples alphabetically
- Sort Array By Parity in Python
- Python – Sort by range inclusion
- Python – Sort by Uppercase Frequency