Home » Programming » Python » Python Sum

How to use the Python sum() Function to Add/Sum Numbers

The Python sum() function takes a list of numbers, and sums them up (totals/adds them all together). Here’s how to use it, with examples.

Summing/Totalling/Adding Numbers

The concept of summing numbers is simple – take the numbers you wish to get the total of, and add them all together.

1 + 2 + 3 = 6

It’s basic arithmetic that you’ll use daily when writing computer software in any language.

Summing Numbers in Python

The sum() function in Python sums numbers. It’s a built-in function, which can be used anywhere in your code without having to import any dependencies.

sum() Syntax

The syntax for the sum() function is as follows:

sum(ITERABLE, START)

Note that:

  • ITERABLE can be any Python iterable, containing numerical values
    • Usually, this is a list of numbers
  • START is an optional starting position within the sequence of supplied numbers to start summing from
    • If not specified, it defaults to 0 (zero)
    • This is an index value, so it starts counting at 0 — the first number in the list is at index 0, the second at index 1, and so on

sum() Examples

Below, a list of numbers is summed:

numberList = [2, 6, 8, 3]

numberSum = sum(numberList)

Only the last 3 numbers in the list can be summed by providing a start position:

numberList = [2, 6, 8, 3]

numberSum = sum(numberList, 1)

Summing Floating Point Numbers with High Accuracy

If you are summing floating point values and require high accuracy in the results, use the math.fsum() function instead.

Otherwise, you are likely to run into floating point precision errors:

sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 

0.9999999999999999

Above, an inaccurate result is returned by the sum() function – the answer should be 1, not 0.9999999999999999math.fsum() will give the correct result:

import math

math.fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])

1.0

Trying to join/concatenate strings?

The syntax for joining strings is the same as adding values in Python – using the + operator.

The sum() function, however, should not be used to join strings. Use the join() method instead.

Concatenating Iterables

Iterables can also be joined together using the itertools.chain() function.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment