Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum a list which contains 'None' using Python

Tags:

python

sum

Basically my question is say you have an list containing 'None' how would you try retrieving the sum of the list. Below is an example I tried which doesn't work and I get the error: TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'. Thanks

def sumImport(self):     my_list = [[1,2,3,None],[1,2,3],[1,1],[1,1,2,2]]     k = sum(chain.from_iterable(my_list))     return k 
like image 553
Sam Avatar asked Sep 01 '12 17:09

Sam


1 Answers

You can use filter function

>>> sum(filter(None, [1,2,3,None])) 6 

Updated from comments

Typically filter usage is filter(func, iterable), but passing None as first argument is a special case, described in Python docs. Quoting:

If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

like image 103
Alexey Kachayev Avatar answered Sep 22 '22 21:09

Alexey Kachayev