Python sum() method


sum is a very useful function in python, but be careful how you use it, the first time I used it, I used it like this.

s = sum(1,2,3)

It's a tragedy. You would see this error:

>>>sum = sum(1,2)
TypeError: 'int' object is not iterable

Actually, sum() is a list, example:

sum([1,2,3])
sum(range(1,11))

There's one more interesting use.

a = range(1,11)
b = range(1,10)
c = sum([item for item in a if item in b])
print(c)

Related course: Complete Python Programming Course & Exercises

python sum() example

The example below shows some more uses of the sum function:

>>>sum = sum([1,2,3])             # in list
6
>>> sum = sum([1,2,3],5)          #in list +start
9
>>> sum = sum((1,2,3))            #in tuple
6
>>> sum = sum({1,2,3})            #in set
6
>>> sum = sum({1:5,2:6,3:7})      #in dictionary key
6
>>> sum = sum(range(1,4))         #in range()

numpy sum

You can also use the sum() function in numpy.

>>> import numpy as np  
>>> a=np.sum([[0,1,2],[2,1,3]])  
>>> a  
9  
>>> a.shape  
()  
>>> a=np.sum([[0,1,2],[2,1,3]],axis=0)  
>>> a  
array([2, 2, 5])  
>>> a.shape  
(3,)  
>>> a=np.sum([[0,1,2],[2,1,3]],axis=1)  
>>> a  
array([3, 6])  
>>> a.shape  
(2,)