Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 227
Alexandru Avatar asked Aug 03 '10 03:08

Alexandru


People also ask

Which returns the number of rows with non null values?

COUNT is an aggregate function that returns a count of the number of rows in a table or column. COUNT returns the BIGINT data type. If the count includes no rows, COUNT returns 0 or NULL, depending on the query.

How do you count the number of specific elements in a list in Python?

The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.

How do you count specific elements in a list?

The count() is a built-in function in Python. It will return the total count of a given element in a list. The count() function is used to count elements on a list as well as a string.


2 Answers

len(filter(None, iterable))

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

like image 103
teepark Avatar answered Oct 09 '22 19:10

teepark


Honestly, I can't think of a better way to do it than what you've got.

Well, I guess people could argue about "better," but I think you're unlikely to find anything shorter, simpler, and clearer.

like image 21
David Z Avatar answered Oct 09 '22 19:10

David Z