- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHPPhysics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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.
Advertisements