How to count non-null elements in an iterable?

Viewed 17836

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

count = sum(1 for e in iterable if e)
9 Answers

As stated in the comments, the title is somewhat dissonant with the question. If we would insist on the title, i.e. counting non-null elements, the OP's solution could be modified to:

count = sum(1 for e in iterable if e is not None)

Here is a solution with O(n) runtime and O(1) additional memory:

count = reduce(lambda x,y:x+y, imap(lambda v: v>0, iterable))

Hope that helps!

Related