
- 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 – 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 −
Example
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)
Output
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)]
Explanation
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.
- Related Articles
- Sort Tuples by Total digits in Python
- Python – Sort Matrix by total characters
- Sort list of tuples by specific ordering in Python
- Python program to Sort Tuples by their Maximum element
- 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 program to sort a list of tuples alphabetically
- Python – Trim tuples by K
- Trim tuples by N elements in Python
- Python – Sort List items on basis of their Digits
- Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple using Python program
- Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple

Advertisements