In this article we’ll go through the Python sum function and it’s uses complete with several examples.

Calculating the sum of values is a common tasks required in many applications. Instead of individually adding each element, why not use an Built-in function instead?

Python gives us the sum() function which has the ability to add all the elements in an iteratable and returns the sum. With one exception that is. A string is in iteratable, but it can be inserted into the sum() function, even if has numbers like '75'.


Syntax

sum(iteratable, start)

The sum function takes two inputs as it’s parameters. The first is the iteratable whose sum needs to be calculated. The second is the starting value. Do not confuse this with starting index or starting point. By default the starting value is zero. But you may instead choose to start the counting from, say 5. If the sum of your list is 10, and the starting value is 5, 15 will be returned.

List

>>> X = [1,2,5,3,6,7]
>>> sum(X)
24

>>> sum(X, 3)
27

Dictionary

This only works so long as the key is a numerical value.

>>> X = {1: "Apple", 2 : "Banana", 3: "Cucumber"}
>>> sum(X)
6

Tuples

Works just like lists. Keep in mind sum can also return float values.

>>> X = (3.4, 6, 3.1)
>>> sum(X)
12.5

Sets

>>> X = {2,8,5,3}
>>> sum(X)
18

range

Useful for generating a list a values, then finding sum. Else you would have to type out, say 100 values. Same concept applies to numpy’s arange function.

>>> r = range(1,101)
>>> sum(r)
5050

This marks the end of the Python sum Function. Any suggestions or contributions for CodersLegacy are more than welcome. Questions can be asked in the comment section below.

Here’s a link back to the main Python Built-in Functions page.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments