Python – Sort Tuples by Total digits

When working with tuples containing numeric data, you might need to sort tuples by the total number of digits across all elements. This involves counting digits in each tuple and using that count as the sorting key.

Method: Using a Custom Function

We can define a function that converts each element to a string, counts the digits, and returns the total ?

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 original tuple is:")
print(my_tuple)

my_tuple.sort(key=count_tuple_digits)

print("The sorted tuple is:")
print(my_tuple)
The original tuple is:
[(32, 14, 65, 723), (13, 26), (12345,), (137, 234, 314)]
The sorted tuple is:
[(13, 26), (12345,), (32, 14, 65, 723), (137, 234, 314)]

Using Lambda Function

You can also use a lambda function for a more concise approach ?

data = [(32, 14, 65, 723), (13, 26), (12345,), (137, 234, 314)]

# Sort using lambda function
sorted_data = sorted(data, key=lambda row: sum(len(str(element)) for element in row))

print("Original:", data)
print("Sorted:", sorted_data)
Original: [(32, 14, 65, 723), (13, 26), (12345,), (137, 234, 314)]
Sorted: [(13, 26), (12345,), (32, 14, 65, 723), (137, 234, 314)]

How It Works

The sorting algorithm counts digits in each tuple:

  • (13, 26) ? 2 + 2 = 4 digits
  • (12345,) ? 5 digits
  • (32, 14, 65, 723) ? 2 + 2 + 2 + 3 = 9 digits
  • (137, 234, 314) ? 3 + 3 + 3 = 9 digits

Reverse Sorting

To sort in descending order (most digits first), add reverse=True ?

def count_tuple_digits(row):
    return sum([len(str(element)) for element in row])

data = [(32, 14, 65, 723), (13, 26), (12345,), (137, 234, 314)]

# Sort in descending order
data.sort(key=count_tuple_digits, reverse=True)

print("Sorted in descending order:")
print(data)
Sorted in descending order:
[(32, 14, 65, 723), (137, 234, 314), (12345,), (13, 26)]

Conclusion

Use a custom function with sort() or sorted() to sort tuples by total digit count. Convert elements to strings and sum their lengths for the sorting key.

Updated on: 2026-03-26T01:03:46+05:30

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements