Alex Rivera | Logout

How to count non-null elements in an iterable?

Asked 2010-08-03T03:40:33.530
20

I'm looking for a better/more Pythonic solution for the following snippet

count = sum(1 for e in iterable if e)
Edit
Report

3 Answers

35
len(list(filter(None, iterable)))

Using None as the predicate for filter just says to use the truthiness of the items. (maybe clearer would be len(list(filter(bool, iterable))))

answered 2010-08-03T03:51:06.780
0

This isn't the fastest, but maybe handy for code-golf

sum(map(bool, iterable))
answered 2010-08-03T03:56:48.587
0

Propably the most Pythonic way is to write code that does not need count function.

Usually fastest is to write the style of functions that you are best with and continue to refine your style.

Write Once Read Often code.

By the way your code does not do what your title says! To count not 0 elements is not simple considering rounding errors in floating numbers, that False is 0..

If you have not floating point values in list, this could do it:

def nonzero(seq):
  return (item for item in seq if item!=0) 

seq = [None,'', 0, 'a', 3,[0], False] 
print seq,'has',len(list(nonzero(seq))),'non-zeroes' 

print 'Filter result',len(filter(None, seq))

"""Output:
[None, '', 0, 'a', 3, [0], False] has 5 non-zeroes
Filter result 3
"""
answered 2010-08-03T07:14:00.943

Your Answer