What is a good way to do countif in Python

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)

Leave a Comment