How to Sum the Digits of a Number in Python?

Problem Formulation

Given an integer number. How to sum over all digits of this number to compute the crossfoot (cross total)?

Consider the following examples:

  • 12 –> 1+2 = 3
  • 123 –> 1+2+3 = 3
  • 244 –> 2+4+4 = 10
  • 981223 –> 9+8+1+2+2+3 = 25

Method 1: sum() with Generator Expression

The Python built-in sum(iterable) function sums over all elements in the iterable. This can be a list, a tuple, a set, or any other data structure that allows you to iterate over the elements.

To sum over all digits of a given integer number, pass the generator expression int(digit) for digit in str(number) into the built-in sum() function. The generator expression converts the number to a string using the built-in str(number) function, iterates over each digit character, and converts each character to an integer. The sum() function sums over all those characters.

number = 123
res = sum(int(digit) for digit in str(number))

print(res)
# 6

You can learn more about the sum() function in this video:

Method 2: map() Function

An alternative way is given next:

To sum over all digits of a given integer number using the map() function, follow these steps:

  • Convert the number to a string using str(number)
  • Pass the result into the map(func, iterable) function as second iterable argument. Pass the built-in int function as a first func argument. This converts each character digit to an integer number.
  • Pass the resulting iterable of integer digits into the sum() function to calculate the sum of all digits.
number = 123
res = sum(map(int, str(number)))

print(res)
# 6

Feel free to watch the following video to dive into the map() function:

Method 3: Fast Integer Only Solution

The previous two solutions convert the integer to a string and the digits back to integers. This is relatively expensive—and not strictly needed. A pure “integer-based” solution accomplishes much better performance:

number = 123
res = 0
while number:
    res += number % 10
    number //= 10
print(res)

The code performs the following steps to calculate the sum of all digits:

  • Start with the result 0.
  • Repeat:
  • … Use in-place addition to add to the current sum of all digits result, the integer value of the last position of the multi-digit number of the modulo result of number % 10. For example, the result of 123 % 10 is 3, i.e., only the value of the last digit.
  • … Remove the last position from the multi-digit number by dividing it by 10 using integer division. For example, the result of 123 // 10 is 12, i.e., the last digit has been removed.
  • End the loop as soon as the number takes on the value 0.

This is by far the fastest solution because it doesn’t need to convert from integer to string and back.

In case you need some background, check out the following video on in-place addition:

Method 4: Closed Formula with only Integers

For most problems, the best solution is, if possible, a closed formula. You plug in the numbers and it quickly calculates the result based on a couple of arithmetic operations. Wouldn’t it be cool to have a closed formula for the sum of all digits problem examined in this article?

Well, this formula exists! 🙂

To calculate the sum of all digits of number n, simply plug n into the following formula n-9*(n-1) // 9. It can be shown with Legendre expanding a sum formula over each digits’ value that this closed formula calculates the sum of all digits.

Here’s the respective code that just plugs in the formula and ensures that the integer input is not 0:

def sum_digits(n):
    return n-9*(n-1) // 9 if n > 0 else 0

print(sum_digits(123))
# 6
print(sum_digits(10000000))
# 1

However, the formula works only on natural (non-negative) numbers. If this is okay with you, this formula will be unbeatable in terms of performance.

To learn about the ternary operator used in the return statement, check out the following video:

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!