Sum() in Python

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
By Rahul Janghu
Free
star4.90
Enrolled: 1000
Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
Rahul Janghu
Free
4.90
icon_usercirclecheck-01Enrolled: 1000
Start Learning

sum() in Python

Overview

The sum() in Python is a built-in function that calculates the sum of elements of an iterable (such as lists, tuples, etc). An optional second offset argument can also be provided as a "starting point" for your sum, by default, it is equal to 0.

Syntax of sum() function in Python

The syntax of sum() is as follows:

Parameters of sum() function in Python

There are two passable parameters while calling sum() in Python:

  • iterable: This is an iterable object like a list, tuple, dictionary, set, etc. This is a required as well as a positional parameter, that is, it can't be left out while calling the function and must be specified as the first argument, respectively.

  • start: This is the second parameter which is optional. This must be of some appropriate type depending on the type of contents of the iterable. Examples below will make this statement more clear. This argument can be passed using both position and name.

Return Value of sum() function in Python

The Return Type can be,

  • integer
  • float
  • complex number

It depends on the type of the contents of the iterable passed in the function. The sum() in Python returns an appropriate value which is equal to

Here sum can refer to numerical sum or concatenation operation for lists and tuples.

Example of sum() function in Python

Let consider a list of numerical elements (that could be integer, floating-point numbers, and complex numbers) to find the sum.

Output:

Explanation:

Since the value of start parameter is 0, therefore the value calculated by sum() function in variable result1 is 1+2+3...9+10 = 55. On the other hand, since we passed a second parameter with start = 4, we got result2 = result1 + start

What is sum() function in Python?

Suppose you have a list of numbers and you want to find their sum. This is quite a common situation that you might encounter while solving many algorithmic or statistical problems, such as finding the mean of a given list of numbers.

The naive way is to iterate through the entire list once using a for-loop or a while-loop and keep adding the values to a sum variable.

Of course, this is not wrong, but wouldn't it be a little annoying and complicated if you have to write this code again and again at multiple places in your program? Well, that's why we make use of functions! You could define your functions, of course, but why bother when Python provides one!

sum() is a built-in function in Python that provides us with a convenient way to find the sum of elements of iterable, such as lists, tuples, sets, and dictionaries basically these are the standard ways of storing and representing a collection of data in Python. We can use the sum function in two major ways as given.

  • If you want to find the exact sum of the contents of your container, then you should follow one of the following syntaxes:

    where the variable iterable is an iterable (like list, tuple, etc.)

  • If you want to find the sum using some offset other than 0 (that is, a different starting point for the sum), then you can use one of the following syntaxes:

    where the variable iterable is the same as specified above, while offset is some appropriate Python object depending on the type of iterable (for example, offset can be a number, a list, etc.).

Implemantation of sum() in Python

We can also implement our own sum() function in Python, as illustrated below. Remember, this is not the exact implementation but successfully imitates the functionality of sum() in Python in most cases. For the exact implementation, you can check out Python's source code.

Code:

Explanation:

We pass param, an iterable (which can be a list, tuple, etc.) to the function mySum() where a for loop iterates over its contents and keeps adding them to the variable sum. In the end, the function returns sum+start, where the value of start is 0 by default.

More Examples

Example 1: Find the sum of a tuple in Python

The steps for finding the sum of elements of a tuple are the same as that of a list. Just call the function by passing the tuple as a parameter.

Code:

Output:

Explanation:

Here we called the sum() function by passing tuples of integers, floating-point numbers, and complex numbers. As you can see, the data types of the corresponding results are also integer, a floating-point, and a complex numbers only.

Example 2: Find the sum of set elements in Python

Just like list and tuple, we can also use sum() in Python to obtain the sum of elements of a set as illustrated below:

Code:

Output:

Explanation:

The sum() functions returns the expected results. Two things are worth noticing in the above example:

  1. While calculating result2, we gave a set of floating-point numbers starting with type complex numbers. Hence in the total sum, we get a complex number with the contents of the set being added to its real part and start as an imaginary part.
  2. While calculating result3, we gave a set of complex numbers with a start value of type floating numbers. As a result, the summation of start ended up being included in the real part.

Example 3: Find the sum of dictionary keys in Python

Surprisingly, the sum() function in Python also works with Python dictionaries. If you pass a dictionary with numeric keys, the function will return the summation of the numeric keys present in that dictionary. The following code examples will help you understand it better.

Code:

Output:

Explanation:

  • In the first function call, we provided the dictionary as input, and it calculated the sum of key values, 1+2+3+4+5+6 = 21.
  • The next function calls sum() to calculate the sum of key values of the dictionary along with an offset value of 4.55. Here you can see some strange behaviour concerning the result's precision (we will discuss it later).
  • In the last function call, we had complex numbers as the key, and consequently, the sum obtained of the key using sum() in Python is also a complex number.

Example 4: Finding the sum of the list which contains floating point number

Code:

Output:

Explanation:

As you can see, the precision of the first output doesn't match the precision of the inputs. But in the second output, it does. This "strange" behaviour is because of how the floating-point operations are handled internally in Python.

Example 5: Passing a List of string and Numbers

Code:

Output:

Explanation:

Here we got an error because while summing up the contents of mylist1, the program encountered a string, which could not be added to the integer using the + operator.

Example 6: String offset along with List of numbers as Iterable

Let's see what will happen if there is a mismatch in the datatypes for the contents of iterable and the start parameter.

Code:

Output:

Explanation:

The error came because when we pass a string as the second parameter to sum(), the program guessed that we're trying to concatenate or sum the strings, and throws an error showing the function sum() in Python cannot sum strings.

Example 7: Passing different data type as offset

Let us see another error case where the data types of iterable and start parameters don't match.

Code:

Output:

Explanation:

Here the contents of the iterable are of type list while the start parameter is of type int, and hence because of this type incompatibility, the program showed an error. You'll get similar errors in other incompatibility cases like when the iterable is a list of tuples, and the start value is either an integer or a list.

Example 8: Using sum function with List of set

Let's see what will happen if the contents of the iterable are not summable under the addition + operator.

Code:

Output:

Explanation:

We can see here that the program gave an error specifying that two set objects are not proper operands for the addition (+) operator. Understand, this is different from the case when we were adding the contents of the set. Here we are trying to somehow add the sets themselves. The same kind of error would be shown if we tried to "add" dictionaries.

But would we get the same error if tried something similar with lists and tuples? The answer is no! Why? It is because lists and tuples possess the concatenation property (similar to strings). A point worth noticing is, the + operator in Python is capable of not only adding numbers but also of concatenating. This is the reason why the sum function in Python would not give an error if we try to "add" them up. See the subsequent example.

Example 9: Using sum function with List of List and Tuple

Code:

Output:

Explanation:

  • In the first case, the sublists present inside the exp1 are concatenated to the empty list [] (given as the start parameter). The final list is shown as the output.
  • In the second part of the code, the tuples present inside the list are concatenated with the tuple (1,3) given as the start parameter.
  • One important thing to observe is that in both these cases, the order of the contents of the lists and tuples are preserved in the final output.

Sum of floating-point numbers in Python

As we saw in earlier examples, using sum over floating-point numbers yields strange results in Python. Therefore, it is recommended to use fsum() function provided in the math module of Python's Standard Library to add floating-point numbers in a list, tuple, etc.

Let's see an example to show the difference in the results we get:

Code:

Output:

Explanation:

  • We can see that fsum() returned the sum with the correct precision, while sum() gave a strange result, because of Python's internal calculation with floating point numbers.
  • Here we called the fsum() function from the imported math module, which is the recommended over sum for adding floating-point numbers. It is important to remember that unlike sum, the fsum doesn't take an optional second argument, that is, it takes only one argument, that is, the iterable.

Python sum() vs NumPy sum()

Numpy, a popular open-source (that is, its source code is publicly available) numeric Python library, also provides us with its own sum() function. So, what's the difference between NumPy's sum() and Python sum() and when to use which? As it turns out:

  • Numpy sum gives better performance with NumPy arrays as inputs
  • Python sum gives better performance with Python objects, such as lists, tuples, etc., as inputs

Reason? Well, Numpy is highly optimized for large matrices and arrays, but it is so because internally these are present as C-arrays rather than Python objects. C-arrays are pointers to locations in memory that can be accessed very efficiently. Python objects are much more abstracted from memory for ease and flexibility in use.

When we call NumPy.sum() and pass a Python object as the iterable, that object is first converted to a C-array. This operation is very time-consuming, and thus delays the result. On the other hand, Numpy arrays are already present in C-array form, thus the Numpy sum operation is very fast (as compared to using Python sum for summing over elements of a Numpy array).

You can also search for some good benchmarking results online for a better comparison.

Conclusion

  1. Python sum() can sum over the elements of iterables such as lists, tuples, dictionaries, sets, but not strings.
  2. We can also provide a second parameter called start while calling the sum() function which acts as an offset/starting value for the sum of the iterables.
  3. This second parameter can be passed as a positional argument as well as a keyword argument. Also, this second argument can never be a string.
  4. Python sum() can also be used to concatenate lists and tuples.
  5. Using sum() with floating-point numbers gives bad precision results, and instead, it is recommended to use the fsum() function present in the math module of Python's standard library.
  6. Using Improper data type with sum function will raise an error.

See Also: