How to sum a list of numbers in python ?

Published: March 14, 2018

DMCA.com Protection Status

Examples of how to sum a list of numbers in python:

Using the sum() function

To add all the elements of a list, a solution is to use the built-in function sum(), illustration:

>>> list = [1,2,3,4]
>>> sum(list)
10

Example with float numbers:

>>> l = [3.1,2.5,6.8]
>>> sum(l)
12.399999999999999

Note: it is possible to round the sum (see also Floating Point Arithmetic: Issues and Limitations):

>>> round(sum(l),1)
12.4

Iterate through the list:

Example using a for loop:

>>> list = [1,2,3,4]
>>> tot = 0
>>> for i in list:
...     tot = tot + i
... 
>>> tot
10

Sum a list including different types of elements

Another example with a list containing: integers, floats and strings:

>>> l = ['a',1,'f',3.2,4]
>>> sum([i for i in l if isinstance(i, int) or isinstance(i, float)])
8.2

Merge a list of "strings":

Note: in the case of a list of strings the function sum() does not work:

>>> list = ['a','b','c','d']
>>> sum(list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

use the function join() instead:

>>> ','.join(list)
'a,b,c,d'
>>> ' '.join(list)
'a b c d'

References