Python Sort list of numbers by sum of their digits (original) (raw)

Last Updated : 15 Jan, 2025

Sorting a list of numbers by the sum of their digits involves ordering the numbers based on the sum of each individual digit within the number. This approach helps prioritize numbers with smaller or larger digit sums, depending on the use case.

Using sorted() with a Lambda Function

sorted() function with a lambda function allows custom sorting by defining a specific key for comparison.

Python `

li = [12, 101, 45, 89, 67]

sorted_numbers = sorted(li, key=lambda x: sum(int(digit) for digit in str(x)))

print(sorted_numbers)

`

Output

[101, 12, 45, 67, 89]

**Explanation:

Using List Comprehension

Using list comprehension with sorted() provides a concise way to create a sorted version of a list based on a custom condition.

Python `

li = [12, 101, 45, 89, 67]

s = [(num, sum(int(digit) for digit in str(num))) for num in li] nums = [num for num, _ in sorted(digit_sums, key=lambda x: x[1])]

print(nums)

`

Output

[101, 12, 45, 67, 89]

**Explanation:

Using a Custom Key Function

digit_sum function calculates the sum of a number's digits by converting the number to a string, iterating over each digit, and summing them. The sorted() function then uses digit_sum as a key to sort the list of numbers in ascending order based on the sum of their digits.

Python `

li = [12, 101, 45, 89, 67]

nums = sorted(li, key=lambda num: sum(int(digit) for digit in str(num)))

print(nums)

`

Output

[101, 12, 45, 67, 89]

**Explanation:

Similar Reads