Skip to content
Related Articles

Related Articles

Python | Sum of number digits in List

View Discussion
Improve Article
Save Article
  • 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 list
test_list = [12, 67, 98, 34]
 
# printing original list
print("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 result
print ("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 list
test_list = [12, 67, 98, 34]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Sum of number digits in List
# using sum() + list comprehension
res = list(map(lambda ele: sum(int(sub) for sub in str(ele)), test_list))
     
# printing result
print ("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 list
test_list = [12, 67, 98, 34]
 
# printing original list
print("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 result
print("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
Recommended Articles
Page :

Start Your Coding Journey Now!