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:
- Key argument of sorted() computes the sum of the digits for each number using a generator expression (sum(int(digit) for digit in str(x))).
- The list is then sorted in ascending order based on these sums.
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:
- First, create a list of tuples containing each number and the sum of its digits.
- Sort the list of tuples by the second element (digit sum).
- Extract the sorted numbers back into a list.
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:
- **lambda num: sum(int(digit) for digit in str(num)) part calculates the sum of the digits of each number in the list by converting the number to a string, iterating over each digit, and summing them up.
- sorted() function sorts the list based on the digit sum of each number, arranging the numbers in ascending order of their digit sums.
Similar Reads
- Sum the Digits of a Given Number - Python The task of summing the digits of a given number in Python involves extracting each digit and computing their total . For example, given the number 12345, the sum of its digits is 1 + 2 + 3 + 4 + 5 = 15. Using modulo (%)This method efficiently extracts each digit using the modulus (%) and integer di 2 min read
- Python - Sort List items on basis of their Digits Given List of elements, perform sorting on basis of digits of numbers. Input : test_list = [434, 211, 12, 3] Output : [12, 211, 3, 434] Explanation : 3 < 12, still later in list, as initial digit, 1 < 3. Hence sorted by digits rather than number. Input : test_list = [534, 211, 12, 7] Output : 2 min read
- Sum of number digits in List in Python Our goal is to calculate the sum of digits for each number in a list in Python. This can be done by iterating through each number, converting it to a string, and summing its digits individually. We can achieve this using Python’s built-in functions like sum(), map(), and list comprehensions. For exa 2 min read
- Python - Sort list of lists by the size of sublists The problem is to sort a list of lists based on the size of each sublist. For example, given the list [[1, 2], [1], [1, 2, 3]], the sorted result should be [[1], [1, 2], [1, 2, 3]] when sorted in ascending order. We will explore multiple methods to do this in Python.Using sorted() with len() This me 3 min read
- Python - Get summation of numbers in string list Sometimes, while working with data, we can have a problem in which we receive series of lists with data in string format, which we wish to accumulate as list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + int() This is the brute force method to perform this 3 min read
- Sort given list of strings by part the numeric part of string - Python We are given a list of strings containing both letters and numbers, and the goal is to sort them based on the numeric part within each string. To do this, we extract the digits, convert them to integers and use them as sorting keys. For example, in ["Gfg34", "is67", "be3st"], the numbers 34, 67, and 3 min read
- Python program to list Sort by Number value in String Given a List of strings, the task is to write a Python program to sort list by the number present in the Strings. If no number is present, they will be taken to the front of the list. Input : test_list = ["gfg is 4", "all no 1", "geeks over 7 seas", "and 100 planets"] Output : ['all no 1', 'gfg is 4 6 min read
- Python - Sort by Units Digit in List Given a Integer list, sort by unit digits. Input : test_list = [76, 434, 23, 22342] Output : [22342, 23, 434, 76] Explanation : 2 < 3 < 4 < 6, sorted by unit digits. Input : test_list = [76, 4349, 23, 22342] Output : [22342, 23, 76, 4349] Explanation : 2 < 3 < 6 < 9, sorted by unit 7 min read
- Sort Numeric Strings in a List - Python We are given a list of numeric strings and our task is to sort the list based on their numeric values rather than their lexicographical order. For example, if we have: a = ["10", "2", "30", "4"] then the expected output should be: ["2", "4", "10", "30"] because numerically, 2 < 4 < 10 < 30. 2 min read
- Python | Convert Stream of numbers to list Sometimes, we can be stuck with a problem in which we are given a stream of space separated numbers with a goal to convert them into a list of numbers. This type of problem can occur in common day-day programming or competitive programming while taking inputs. Let's discuss certain ways in which thi 5 min read