Python | Sum of number digits in List

• Difficulty Level : Medium
• Last Updated : 30 Jun, 2021

The problem of finding the summation of digits of numbers is quite common. This can sometimes come in form of a list and we need to perform that. This has application in many domains such as school programming and web development. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using loop + str()
This is brute force method to perform this particular task. In this, we run a loop for each element, convert each digit to string, and perform the count of the sum of each digit.

Python3

 # Python3 code to demonstrate# Sum of number digits in List# using loop + str() # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint("The original list is : " + str(test_list)) # Sum of number digits in List# using loop + str()res = []for ele in test_list:    sum = 0    for digit in str(ele):        sum += int(digit)    res.append(sum)     # printing resultprint ("List Integer Summation : " + str(res))
Output :
The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]

Method #2 : Using sum() + list comprehension
This task can also be performed using shorthand using above functionalities. The sum() is used to compute summation and list comprehension is used to compute iterations.

Python3

 # Python3 code to demonstrate# Sum of number digits in List# using sum() + list comprehension # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint("The original list is : " + str(test_list)) # Sum of number digits in List# using sum() + list comprehensionres = list(map(lambda ele: sum(int(sub) for sub in str(ele)), test_list))     # printing resultprint ("List Integer Summation : " + str(res))
Output :
The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]

Method #3 : Using sum() + reduce()
This task can also be performed using shorthand using the above functionalities. The sum() is used to compute summation and reduce function from functools module.

Python3

 # Python3 code to demonstrate# Sum of number digits in a List# using sum() + reduce()from functools import reduce # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint("The original list is : " + str(test_list)) # Sum of number digits in List# using sum() + reduce()res = [reduce(lambda x, y: int(x) + int(y), list(str(i))) for i in test_list] # printing resultprint("List Integer Summation : " + str(res))

Output:

The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]

My Personal Notes arrow_drop_up