3 ways to find sum of numbers in an iterable in Python


To find the sum of numbers in an iterable in Python, we can

  • Use the built-in sum() function
  • Use a loop
  • Use recursion

In today’s post, we’ll discuss how to use each of the methods above and highlight some of the things to take note when using the built-in sum() function.

For our practice question, we’ll work on a function that accepts multiple inputs (of various data types) and returns the sum of all numerical inputs.

Here are some concepts we’ll cover in today’s post:

  • How to find sum of numbers in an iterable in Python
  • How to use recursion
  • The difference between the sum() and fsum() functions

How to find the sum of numbers in an iterable

Using the built-in sum() function

The easiest way to find the sum of numbers in an iterable is to use a built-in function called sum(). This function accepts two arguments – the iterable to sum and an optional value to add to the sum. Its syntax is as follows:

sum(iterable, value_to_add)

If the function is unable to sum the numbers in the iterable, it throws a TypeError exception. Let’s look at some examples:

Finding sum of numbers in a list, set, dictionary and tuple

#Sum numbers in a list
myList = [1, 2, 3.5, 2.1, 6]
print(sum(myList))

#Sum numbers in a set
mySet = {1, 5, 2.7, 8}
print(sum(mySet))

#Sum numbers in a dictionary
myDict = {1:101, 2:102, 3:103, 4:104}
print(sum(myDict))

#Sum numbers in a tuple
myTuple = (1, 2, 6.7, 1.1, 5)
print(sum(myTuple))

If you run the code above, you’ll get the following output:

14.6
16.7
10
15.799999999999999

The sum() function adds the numbers in an iterable and returns the result.

For instance, in the first example, the function adds the numbers in myList (1 + 2 + 3.5 + 2.1 + 6) and returns 14.6 as the result.

In the second example, the function adds the numbers in mySet (1 + 5 + 2.7 + 8) and returns 16.7 as the result.

In the third example, we pass a dictionary to the sum() function. When we do that, the function sums the keys of the dictionary, not the values. Hence, we get 1 + 2 + 3 + 4 = 10 as the result.

Finally, in the fourth example, the function sums the values in myTuple and returns the result. However, notice that the result is not exact? Instead of getting 1 + 2 + 6.7 + 1.1 + 5 = 15.8, we get 15.799999999999999.

This is not due to a bug in our code or in Python. Rather, it has to do with the way floating-point numbers (i.e. numbers with decimal parts) are represented in our computers. We’ve seen another example of this issue previously when we learned to square a number in Python.

If you are interested in finding out more about how floating-point numbers work, you can check out the following website: https://docs.python.org/3/tutorial/floatingpoint.html

If you need to ensure that you always get an exact result when finding the sum of floating-point numbers, you can use another function called fsum(). We’ll discuss this function in a later section.

Passing a second argument to the sum() function

Next, let’s look at an example of how the second argument for the sum() function works.

If we do not pass any value for the second argument, the sum() function simply adds the numbers in the iterable and returns the result. However, if we pass a value for the second argument, the function adds the value of the argument to the sum of numbers in the iterable. Let’s look at an example:

myList = [1, 2, 3.5, 2.1, 6]

#Without second argument
print(sum(myList))

#With second argument
print(sum(myList, 1000))

If you run the code above, you’ll get the following output:

14.6
1014.6

Passing invalid arguments to the sum() function

Last but not least, let’s look at what happens when we pass an invalid argument to the sum() function.

When that happens, the function throws a TypeError exception. Examples of invalid arguments include passing a string to the function, or passing a list that includes strings as elements.

For instance, the examples below will all give us a TypeError exception if we try to run them.

myString = '123456'
print(sum(myString))

myStrList = [1, 2, 3, '4', 5]
print(sum(myStrList))

myList = [1, 2, 3.5, 2.1, 6]
print(sum(myList, '100'))

myList2 = [1, 2, 3, 4, [1, 5]]
print(sum(myList2))

The first three examples fail as the sum() function does not work with strings. If we pass a string to the function, the function throws an exception. The last example fails as myList2 contains a nested list.

Using a loop

Now that we are familiar with the built-in sum() function, let’s proceed to discuss how we can use a loop to find the sum of numbers in an iterable.

The code below shows an example of using a for loop to sum the numbers in a list:

myList = [1, 2, 3.5, 2.1, 6]
sum = 0

for i in myList:
    sum += i

print(sum)

On lines 1 and 2, we declare and initialize two variables – myList and sum.

Next, we use a for loop to iterate through myList. For each element in myList, we add its value to sum (on line 5).

After we finish iterating through myList, we use the print() function (outside the for loop) to print the value of sum.

If you run the code above, you’ll get

14.6

as the output.

Using a for loop gives us more flexibility in terms of what we want to sum. For instance, if we use the built-in sum() function to sum the elements in a dictionary, it returns the sum of the keys in the dictionary. If we want to sum the values instead, we can use a for loop:

myDict = {1:101, 2:102, 3:103, 4:104}
sum = 0

for i in myDict:
    sum += myDict[i]

print(sum)

When we use a for loop to iterate through a dictionary, Python accesses the key of the items in the dictionary, not the value. For instance, in the for loop above, i stores the keys of the items in myDict.

If we want to sum the values of the items, we need to add myDict[i] (instead of i) to sum, as shown in line 5 above.

If you run the code above, you’ll get the following output:

410

The loop sums the values in myDict. Hence, we get 101 + 102 + 103 + 104 = 410 as the output.

Using recursion

Next, let’s discuss the final method to find the sum of numbers in an iterable. This method involves using recursion. We’ve discussed recursion multiple times in previous posts. If you are not familiar with recursion, you should definitely check out some of those posts (e.g. here and here).

Technically speaking, using recursion is kind of unnecessary in this case, as using the built-in sum() function or a simple loop is much more straightforward. However, recursion can be a very powerful technique for solving more complex questions like a Sudoku or permutation problem. Hence, it helps to see more examples of how recursion works, especially with easier questions like the current one.

As mentioned previously, recursion can be used to solve problems where solution to the problem relies on solving smaller instances of the same problem.

When it comes to finding the sum of numbers in an iterable, suppose we have a list with five numbers. We can find the sum of all five numbers by adding the first number to the sum of the remaining four numbers (a smaller instance of the same problem).

This can be easily implemented using recursion.

myList = [1, 2, 3.5]

def sumRec(iterToSum):
    if len(iterToSum) > 1:
        return iterToSum [0] + sumRec(iterToSum [1:])
    else:
        return iterToSum [0]

print(sumRec(myList))

Here, we first declare and initialize a list called myList.

Next, we define a function called sumRec() (from lines 3 to 7) that has one parameter – iterToSum.

Inside the function, we check if the length of iterToSum is greater than 1 (line 4). If it is, we add the first element in iterToSum (i.e. iterToSum [0]) to the result of sumRec(iterToSum[1:]) and return the sum (line 5).

sumRec(iterToSum[1:]) represents a smaller instance of sumRec(iterToSum).

While the latter sums all numbers in iterToSum, the former sums all elements except the first (as the slice [1:] selects all elements starting from index 1 to the end of the list).

We keep calling the sumRec() function recursively until the length of the list we pass to it is no longer greater than 1. When that happens, we have what is known as a base case (lines 6 and 7).

A base case is the case the stops the recursion. When the length of the list to sum is no longer greater than 1, we do not need to use recursion to find the sum of the elements in the list. As there is only one element in the list now, the sum is simply the number itself. For instance, the sum of [12] is simply 12.

Once we reach the base case, the recursion stops and the result is returned to the caller of each recursive call. This gives us the result of the sum of all numbers in the list.

To see how this works, let’s suppose we call the sumRec() function with [1, 2, 3.5] as the argument.

The recursive calls and return values are shown in the diagram below:

recursive function to find sum of numbers in iterable

Line 9 starts by calling sumRec([1, 2, 3.5]), which in turn calls sumRec([2, 3.5]), which calls sumRec([3.5]).

sumRec([3.5]) is the base case. It returns 3.5 to its caller sumRec([2, 3.5]).

sumRec([2, 3.5]) (which is not a base case) in turn returns 2 + sumRec([3.5]) = 2 + 3.5 = 5.5 to its caller sumRec([1, 2, 3.5]).

sumRec([1, 2, 3.5]) (which is also not a base case) returns 1 + sumRec([2, 3.5]) = 1 + 5.5 = 6.5 to its caller line 9.

Therefore, if you run the code above, you’ll get

6.5

as the output.

That’s it. That’s how recursion can be used to help us find the sum of numbers in an iterable. You may need to read through this section more than once to fully appreciate how recursion works.

Working with floating-point numbers

We’ve covered three main ways to find the sum of numbers in an iterable in Python. Now, let’s move on to a topic we skipped previously.

In the previous section, we learned to use the built-in sum() function to sum numbers in an iterable. While this function is very easy to use, we saw that it does not always return an exact value. For instance, when we pass the tuple (1, 2, 6.7, 1.1, 5) to the function, we get 15.799999999999999 as the output.

If it is crucial for us to get an exact answer when finding the sum of numbers in an iterable, we should use another built-in function – fsum().

This function is available in the math module.

Let’s look at an example:

import math

myTuple = (1, 2, 6.7, 1.1, 5)

#Using sum()
print(sum(myTuple))

#Using fsum()
print(math.fsum(myTuple))

If you run the code above, you’ll get the following output:

15.799999999999999
15.8

The fsum() is very similar to the sum() function. The main difference is that the fsum() function gives an exact output while the sum() function does not always do that.

Another difference is the fsum() does not have a second optional argument. Other than that, the two functions are very similar.

That’s it. We are now ready to proceed to the practice question for today.

Practice Question

Today’s practice question requires us to write a function called mySum() that prompts users to enter a list of values, separated by commas. The values entered can be of any data type. For instance, they can be text, symbols, or numbers. The function needs to return the sum of all the numbers entered. This sum should be rounded off to 2 decimal places.

Expected Results

To test your function, you can run the function and enter the following inputs:

1, 2, 3.1, 4, hello, [2, 3], #, $

The function should return 10.1 as the result.

Suggested Solution

The suggested solution is as follows:

Click to see the suggested solution
def mySum():
    userInput = input('Pleae enter the values, separated by commas: ')
    myList = userInput.split(',')

    result = 0

    for i in myList:
        try:
            result += float(i)
        except:
            pass

    return round(result, 2)

sumOfNumbers = mySum()
print(sumOfNumbers)

In the code above, we first define a function called mySum() on line 1.

Inside the function, we use the built-in input() function to prompt users for an input. This function prompts users for an input and returns the input as a string. We store this string in a variable called userInput.

Next, we use a built-in function called split() to split userInput into a list of substrings, using a comma (https://docs.python.org/3/library/stdtypes.html#str.split) as the delimiter. If the input string is '1, 2, 3, 4, 5', we’ll get ['1', ' 2', ' 3', ' 4', ' 5'] as the result, which we store in a variable called myList.

Next, we declare and initialise a variable called result.

We then use a for loop to iterate through myList.

Inside the for loop, we use a try-except statement to try converting i to a float. If that can be done, we add the value of the resulting float to result (line 9).

On the other hand, if i cannot be converted to a float, the float() function throws an exception and the except block is executed. Inside the except block (lines 10 to 11), we use the pass statement to indicate that we do not want to do anything when i cannot be converted to a float.

After we finish iterating through all the elements in myList, we use the round() function to round the sum to 2 decimal places and use the return statement to return the result.

With that, the function is complete.

Written by Jamie | Last Updated October 25, 2020

Recent Posts