Sort Tuples by Total digits in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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.

raja
Published on 14-Apr-2021 14:16:45
Advertisements