Open In App

Python | Sum of number digits in List

Last Updated : 16 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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]

Time Complexity: O(n*m)
Auxiliary Space: O(n)

 
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]

Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list.

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.

Python
# 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]

Method #4 : Using numpy

Note: Install numpy module using command “pip install numpy”

Here’s one approach using numpy:

Python
import numpy as np

# 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 numpy
res = np.sum([list(map(int, str(ele))) for ele in test_list], axis=1)

# printing result
print("List Integer Summation : " + str(list(res)))

Output:

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

Method #5 : Using itertools library:

Python
# Python3 code to demonstrate 
# Sum of number digits in List
# using itertools library
# importing itertools library
import itertools
# 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 itertools library
res = [sum(map(int, list(itertools.chain(*str(ele))))) for ele in test_list]
# printing result 
print ("List Integer Summation : " + str(res))
#This code is contributed by Jyothi pinjala.

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

Time Complexity: O(n*m)
Auxiliary Space: O(n)

Method #6 : Using map() function and modulo operator :

Step-by-step algorithm for implementing the approach

1) First, define a function digit_sum(num) which takes a single number as input and returns the sum of its digits

  • Initialize a variable digit_sum to 0.
  • Apply a while loop to extract the last digit of the number using the modulo operator (%) and add it to the digit_sum variable.
  • Divide the number by 10 using floor division operators (//) to remove the last digit.
  • Repeat sub point 2 and 3 until the number becomes zero.
  • Return the digit_sum variable.

2) Define a function sum_of_digits_list(lst) which will takes a list of numbers as input and returns a list containing the sum of digits of each number in the input list, using the following steps:

  • Apply map() function to the digit_sum() function.
  • Convert the resulting map object to a list using the list() function.
  • Return the resulting list.

3) Define a list of numbers lst which will calculate the sum of digits.

4) Now wecall the sum_of_digits_list(lst) function with lst as the input.

5) Print the resulting list.

Code :

Python
lst = [12, 67, 98, 34]
def digit_sum(num):
    digit_sum = 0
    while num > 0:
        digit_sum += num % 10
        num //= 10
    return digit_sum

def sum_of_digits_list(lst):
    return list(map(digit_sum, lst))

print(sum_of_digits_list(lst))

Output
[3, 13, 17, 7]

Time Complexity: O(nlog(n)) where n is the value of the input number. This is because the map() function applies the digit_sum() function to each element of the input list, which has a time complexity of O (log n) for each element. 
Auxiliary Space: O(n)  because it creates a list of length n to store the result of the map() function.

Method #7: Creating a expression without changing to a string

  • For each elem in the list, the inner list creates a new list that consists of the sum of the individual digits.
  • The str() function converts the integer to a string.
  • The int() function converts each digit back to an integer.
  • The sum() function finds the sum.
  • The outer list adds the sum calculated in step 4 to a new list.
Python
# 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
# creating an expression
res = list(sum(int(digit) for digit in str(num)) for num in test_list)
# printing result
print("List Integer Summation : " + str(list(res)))

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

Time Complexity: O(N*M) where N is the elements in the list and M is the average number of digits in each element.

Auxiliary Space: O(N) as we create a new list of the same size.



Similar Reads

Sum of the digits of square of the given number which has only 1's as its digits
Given a number represented as string str consisting of the digit 1 only i.e. 1, 11, 111, .... The task is to find the sum of digits of the square of the given number. Examples: Input: str = 11 Output: 4 112 = 121 1 + 2 + 1 = 4 Input: str = 1111 Output: 16 Naive approach: Find the square of the given number and then find the sum of its digits. Below
6 min read
Python | Sort list of numbers by sum of their digits
Given a list of non-negative numbers, the task is to sort these integers according to the sum of their digits. Examples: Input : [12, 10, 106, 31, 15] Output : [10, 12, 31, 15, 106] Input : [1111, 19, 29, 11, 12, 9] Output : [11, 12, 1111, 9, 19, 29] Let's discuss few Pythonic ways to do this task. Approach #1 : List comprehension Using for loop to
4 min read
Python program to find the sum of all even and odd digits of an integer list
The following article shows how given an integer list, we can produce the sum of all its odd and even digits. Input : test_list = [345, 893, 1948, 34, 2346] Output : Odd digit sum : 36 Even digit sum : 40 Explanation : 3 + 5 + 9 + 3 + 1 + 9 + 3 + 3 = 36, odd summation.Input : test_list = [345, 893] Output : Odd digit sum : 20 Even digit sum : 12 Ex
5 min read
Python Program for Sum the digits of a given number
Given a number and the task is to find sum of digits of this number in Python. Examples: Input : n = 87 Output : 15 Input : n = 111 Output : 3 Below are the methods to sum of the digits. Method-1: Using str() and int() methods.: The str() method is used to convert the number to string. The int() method is used to convert the string digit to an inte
2 min read
Python | Ways to sum list of lists and return sum list
The list is an important container and is used almost in every code of day-day programming as well as web development, more it is used, the more is the requirement to master it and hence knowledge of its operations is necessary. Given a list of lists, the program to suppose to return the sum as the final list. Let's see some of the methods to sum a
5 min read
Check if the sum of digits of a number N divides it
Given a number N. The task is to check if the sum of digits of the given number divides the number or not. If it divides it then print YES otherwise print NO.Examples: Input : N = 12Output : YESSum of digits = 1+2 =3 and 3 divides 12.So, print YES.Input : N = 15Output : NORecommended: Please try your approach on {IDE} first, before moving on to the
10 min read
Python | Remove all digits from a list of strings
Given a list of strings, write a Python program to remove all digits from the list of string. Examples: Input : ['alice1', 'bob2', 'cara3'] Output : ['alice', 'bob', 'cara'] Input : ['4geeks', '3for', '4geeks'] Output : ['geeks', 'for', 'geeks'] Method #1: Python Regex Python regex pattern can also be used to find if each string contains a digit or
5 min read
Python | Convert list of tuples into digits
Given a list of tuples, the task is to convert it into list of all digits which exists in elements of list. Let’s discuss certain ways in which this task is performed. Method #1: Using re The most concise and readable way to convert list of tuple into list of all digits which exists in elements of list is by using re. C/C++ Code # Python code to co
6 min read
Python | Checking if starting digits are similar in list
Sometimes we may face a problem in which we need to find a list if it contains numbers with the same digits. This particular utility has an application in day-day programming. Let's discuss certain ways in which this task can be achieved. Method #1: Using list comprehension + map() We can approach this problem by converting the elements to the stri
8 min read
Python | Remove element from given list containing specific digits
Given a list, the task is to remove all those elements from list which contains the specific digits. Examples: Input: lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] no_delete = ['2', '3', '4', '0'] Output: [1, 5, 6, 7, 8, 9, 11, 15, 16] Explanation: Numbers 2, 3, 4, 10, 12, 13, 14 contains digits from no_delete, therefore remove them
9 min read
Practice Tags :