Python sum()

The sum() function adds the items of an iterable and returns the sum.

The syntax of sum() is:

sum(iterable, start)

The sum() function adds start and items of the given iterable from left to right.


sum() Parameters

  • iterable - iterable (list, tuple, dict etc) whose item's sum is to be found. Normally, items of the iterable should be numbers.
  • start (optional) - this value is added to the sum of items of the iterable. The default value of start is 0 (if omitted)

Return Value from sum()

The sum() function returns the sum of start and items of the given iterable.


Example: How sum() function works in Python?

numbers = [2.5, 3, 4, -5]

# start parameter is not provided
numbersSum = sum(numbers)
print(numbersSum)

# start = 10
numbersSum = sum(numbers, 10)
print(numbersSum)

When you run the program, the output will be:

4.5
14.5

If you need to add floating point numbers with exact precision then, you should use math.fsum(iterable) instead

If you need to concatenate items of the given iterable (items must be string), then you can use join() method.

''.join(sequence)

Visit this page to learn about, Python join() Method