Sum the Digits of a Given Number - Python
Last Updated :
15 Jul, 2025
The task of summing the digits of a given number in Python involves extracting each digit and computing their total . For example, given the number 12345, the sum of its digits is 1 + 2 + 3 + 4 + 5 = 15.
Using modulo (%)
This method efficiently extracts each digit using the modulus (%) and integer division (//) operations, avoiding unnecessary string conversions. It is the fastest and most memory-efficient approach, making it ideal for performance-focused applications.
Python
n = 12345
sum = 0
while n > 0:
sum += n % 10 # extract last digit
n //= 10 # remove last digit
print(sum)
Explanation: This code iterates through the digits of n, extracting each last digit using % 10, adding it to sum and removing it with // 10 until n becomes 0.
Using recursion
This method uses recursion to break the problem into smaller subproblems. It follows the same mathematical approach but introduces function call overhead, making it slightly less efficient than the iterative method. It is useful when a recursive solution is preferred.
Python
# recursive function
def fun(n):
if n == 0:
return 0 # base case
return (n % 10) + fun(n // 10)
n = 12345
print(fun(n))
Explanation: fun(n) recursively sums the digits of n. If n is 0, it returns 0. Otherwise, it adds the last digit (% 10) to the sum of a recursive call on the remaining digits (// 10), repeating until n becomes 0.
Using map()
map() apply the int() conversion directly, reducing memory usage. It provides a more functional programming style but still involves string conversion and making it less efficient than mathematical methods.
Python
n = 12345
sum = sum(map(int, str(n)))
print(sum)
Explanation: This code converts n to a string, maps each digit to an integer and sums them using sum().
Using reduce
functools.reduce() applies a cumulative operation to the digits. Although some may prefer this approach, it adds unnecessary function call overhead, making it the least efficient method for this problem.
Python
from functools import reduce
n = 12345
sum = reduce(lambda x, y: x + int(y), str(n), 0)
print(sum)
Explanation: This converts n to a string, then applies a lambda function that iteratively adds each digit (converted to an integer) to an accumulator, starting from 0.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice