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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With