How to sum a list of numbers in python ?

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)

Example with float numbers:

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

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

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

Iterate through the list:

Example using a for loop:

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

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)])

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)
>>> ' '.join(list)
'a b c d'