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 example, given the list [123, 456, 789], we will calculate the sum of digits for each number, resulting in a list of sums such as [6, 15, 24].
Using Loops
This code calculates the sum of digits for each number in the list a using a while loop and stores the results in the res list.
a = [123, 456, 789]
res = []
for val in a:
total = 0
while val > 0:
total += val % 10
val //= 10
res.append(total)
print(res)
Output
[6, 15, 24]
Explanation:
- The code loops through each number in the list a, extracting and summing its digits.
- It uses the modulo operator (%) to get the last digit and integer division (//) to remove the last digit, continuing this until the number is reduced to zero.
- The sum of digits for each number is stored in the list res.
Using List Comprehension
List comprehension offers a more concise way to sum digits. This code calculates the sum of digits for each number in the list a using a list comprehension and stores the results in the res list.
a = [123, 456, 789]
res = [sum(int(digit) for digit in str(val)) for val in a]
print(res)
Output
[6, 15, 24]
Explanation:
- str(val) converts the number to a string so we can loop through its digits.
- int(digit) converts each string digit back to an integer for summing.
- The list comprehension sums the digits of each number in the list.
Using map Function
map() function is a functional approach that applies a function to each element in the list.
a = [123, 456, 789]
res = list(map(lambda val: sum(int(digit) for digit in str(val)), a))
print(res)
Output
[6, 15, 24]
Explanation: The lambda function directly computes the sum of digits and map() function is used to map this lambda function for each value in the list “a”.
Related Articles: