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.


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.


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.


sum() with tuple of integers

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


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.


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.


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.


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.


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