
- 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
Sort Tuples by Total digits in Python
When it is required to sort the element in a list of tuple based on the digits, the ‘sorted’ method and the lambda function can be used.
Below is a demonstration for the same −
Example
my_list = [(11, 23, 45, 678), (34, 67), (653,), (78, 99, 23, 45), (67, 43)] print("The list is : ") print(my_list) my_result = sorted(my_list, key = lambda tup : sum([len(str(ele)) for ele in tup ])) print("The sorted tuples are ") print(my_result)
Output
The list is : [(11, 23, 45, 678), (34, 67), (653,), (78, 99, 23, 45), (67, 43)] The sorted tuples are [(653,), (34, 67), (67, 43), (78, 99, 23, 45), (11, 23, 45, 678)]
Explanation
A list of tuple is defined, and is displayed on the console.
The lambda function is used to iterate through the list of tuple, and get the length of every element after converting every element into a string data type.
This is sorted using the ‘sort’ method.
This value is assigned to a variable.
This is displayed on the console.
- Related Articles
- Python – Sort Tuples by Total digits
- Sort list of tuples by specific ordering in Python
- Python – Sort Matrix by total characters
- Python program to Sort Tuples by their Maximum element
- Sort Tuples in Increasing Order by any key in Python program
- Python program to sort tuples in increasing order by any key.
- Convert list of tuples into digits in Python
- Python program to sort a list of tuples by second Item
- Python program to sort tuples by frequency of their absolute difference
- Python program to sort a list of tuples alphabetically
- Python – Trim tuples by K
- Trim tuples by N elements in Python
- 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
- Python – Sort List items on basis of their Digits

Advertisements