Last Updated : 12 Jul, 2025
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 LoopsThis 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.
Python
a = [123, 456, 789]
res = []
for val in a:
total = 0
while val > 0:
total += val % 10
val //= 10
res.append(total)
print(res)
Explanation:
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.
Python
a = [123, 456, 789]
res = [sum(int(digit) for digit in str(val)) for val in a]
print(res)
Explanation:
map() function is a functional approach that applies a function to each element in the list.
Python
a = [123, 456, 789]
res = list(map(lambda val: sum(int(digit) for digit in str(val)), a))
print(res)
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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4