Python – Sort Tuples by Total digits

PythonServer Side ProgrammingProgramming

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

 Live Demo

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.

raja
Published on 06-Sep-2021 08:11:07
Advertisements