Search code examples
pythoniteratorlist-comprehensionidioms

How to count non-null elements in an iterable?


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

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

Solution

  • 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))))