I want to count how many members of an iterable meet a given condition. I'd like to do it in a way that is clear and simple and preferably reasonably optimal.
My current best ideas are:
sum(meets_condition(x) for x in my_list)
len([x for x in my_list if meets_condition(x)])
The iterator based approach is just fine. There are some slight modifications that can emphasize the fact that you are counting:
sum(1 if meets_condition(x) else 0 for x in my_list) # or sum(1 for x in my_list if meets_condition(x))
And as always, if the intent isn't apparent from the code, encapsulate it in descriptively named function:
def count_matching(condition, seq): """Returns the amount of items in seq that return true from condition""" return sum(1 for item in seq if condition(item)) count_matching(meets_condition, my_list)