I'm looking for a better/more Pythonic solution for the following snippet
count = sum(1 for e in iterable if e)
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.
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.
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.
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))
)
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.
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