Sum of Number Digits in List in Python
Given a list of integers, write a Python program to calculate the sum of digits for each element and store the results in a new list. For Example:
Input: [123, 456, 789]
Output: [6, 15, 24]
Explanation: 123 = 1 + 2 + 3 = 6
456 = 4 + 5 + 6 = 15
789 = 7 + 8 + 9 = 24
Below are the different methods to perform this task:
Using List Comprehension
This method uses a single-line expression to compute the sum of digits for each number efficiently.
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 each number to a string for digit iteration.
- int(digit): converts each character back to an integer.
- sum(): function calculates the total of digits for each number.
Using map() with lambda Function
This functional approach uses map() to apply a lambda function on each element of 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:
- lambda val: defines an inline function to sum digits.
- map(): applies this function to every element in the list.
- list(): converts the result back into a list.
Using Loops
This method uses simple for and while loops to manually extract and sum digits.
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:
- val % 10: extracts the last digit.
- val //= 10: removes the last digit.
- Each sum is appended to res.
Using sum() and map() function
This method combines sum() and map() without lambda for a cleaner approach.
a = [123, 456, 789]
res = [sum(map(int, str(val))) for val in a]
print(res)
Output
[6, 15, 24]
Explanation:
- map(int, str(val)): converts digits to integers directly.
- sum(): adds them up for each number.
- The list comprehension collects the results.
Related Articles: