ScanSkill

sum

This sum() function returns a total(sum) of the items contained in the iterable object.

Syntax

sum(*iterable[, start]*)
sum(iterable, start)

Here,

  • iterable: Required. Must be a sequence, an iterator, or some other object which supports iteration.
  • start: Optional. An integer specifying the initial start value. Default is 0.

Note: There are other good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling “”.join(sequence). Also for floating point values with extended precision, math.fsum() is a great alternative. To concatenate a series of iterables, consider using itertools.chain().

Examples

  • With list, tuple, set, and dictionary
>>> sum([1, 2, 3])
6 # 1+2+3
>>> sum((1, 2, 3))
6
>>> sum({1, 2, 3})
6
>>> sum({1: 'a', 2: 'b', 3: 'c'})
6
  • With start parameter value
>>> sum([1, 2, 3], 100)
106
>>> sum((1, 2, 3), 100)
106
106
>>> sum({1, 2, 3}, 100)
106
>>> sum({1: 'a', 2: 'b', 3: 'c'}, 100)
106
  • With float types
>>> sum([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
0.9999999999999999

>>> import math
>>> math.fsum([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
1.0