Sum a list which contains 'None' using Python
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
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.
Remove None
(and zero) elements before summing by using filter
:
>>> k = sum(filter(None, chain.from_iterable(my_list)))
>>> k
20
To see why this works, see the documentation for filter
:
filter(function, iterable)
Construct a list from those elements of
iterable
for whichfunction
returns true.iterable
may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function isNone
, the identity function is assumed, that is, all elements of iterable that are false are removed.Note that
filter(function, iterable)
is equivalent to[item for item in iterable if function(item)]
if function is notNone
and[item for item in iterable if item]
if function isNone
.