w3resource

Python: Compute the sum of digits of each number of a given list of positive integers


34. Sum of Digits for Each Number

Write a Python program to compute the sum of digits of each number in a given list of positive integers.

Sample Solution:

Python Code:

from itertools import chain
def sum_of_digits(nums):
    return sum(int(y) for y in (chain(*[str(x) for x in nums])))

nums = [10,2,56]
print("Original tuple: ") 
print(nums)
print("Sum of digits of each number of the said list of integers:")
print(sum_of_digits(nums))

nums = [10,20,4,5,70]
print("\nOriginal tuple: ") 
print(nums)
print("Sum of digits of each number of the said list of integers:")
print(sum_of_digits(nums))

Sample Output:

Original tuple: 
[10, 2, 56]
Sum of digits of each number of the said list of integers:
14

Original tuple: 
[10, 20, 4, 5, 70]
Sum of digits of each number of the said list of integers:
19

For more Practice: Solve these Related Problems:

  • Write a Python program to compute the sum of digits for each number in a list and then filter out numbers with a digit sum below a certain threshold.
  • Write a Python program to use map to convert each positive integer into the sum of its digits and then return a list of these sums.
  • Write a Python program to generate a new list where each element is the sum of digits of the corresponding number from the original list, using a lambda.
  • Write a Python program to calculate the sum of digits for each number and then use filter to retain only numbers with an even digit sum.

Go to:


Previous: Write a Python program to find the pairs of maximum and minimum product from a given list. Use itertools module.

Next: Write a Python program to get all possible combinations of the elements of a given list using itertools module.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.