- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- 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
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.
Advertisements