Python sum() Function

Python sum() Function

The built-in Python sum() function is another powerful tool anytime you’re working with numerical data in Python. The first argument to the sum() function should be a collection of numbers that you would like to add up. These numerical values can be contained within a list, tuple, set, or dictionary. The optional second parameter to use with the sum() function is the ‘start’ parameter. This adds a numeric value to the final result. If you try to use a non-numeric data type with sum(), Python will throw an error. Let’s look at several examples of how sum() works now.


sum() with list of integers

The first example shows a list of integers stored in a variable. We can pass that variable to the sum() function, and it adds them all up and returns the result to us.

36

sum() with list of floating-point numbers

Example two of sum() has a list of floating-point values. We again pass that list of floating-point numbers to the sum() function, and it gives us the result faster than we could ever do it in our head.

39.32340000000001

sum() with list of integers and optional start

Example three of sum() does make use of the optional start parameter. We can see that we are adding 1 + 1, which of course is 2. Since we used a starting point of 10 however, the final result is actually 12.

12

sum() with tuple of integers

Example four of the sum() function adds up all of the integer values stored in a tuple.

16

sum() with tuple of floating-point numbers

In example five of the sum() function, we add up some floating point vaues that are stored in a tuple.

17.66

sum() with tuple of integers and optional start

Example six shows how to use sum() with a tuple of integers and the optional start parameter.

36

sum() with a set

Example seven is interesting because we use a set with the sum() function. The result below when adding 2 + 2 + 4 gives a result of 6. How? This is because the set removes the duplicate 2’s before completing the sum operation.

6

sum() with a dictionary

The last example of the sum() function that we can look at is summing the values of keys in a dictionary.

14

If you would rather sum all of the values of a dictionary in Python, you can do so like this:

12