What is a good way to do countif in Python

countif for a list

#counting if a number or string is in a list
my_list=[1,2,3,2,3,1,1,1,1,1, "dave" , "dave"]
one=sum(1 for item in my_list if item==(1))
two=sum(1 for item in my_list if item==(2))
three=sum(1 for item in my_list if item==(3))
dave=sum(1 for item in my_list if item==("dave"))
print("number of one's in my_list > " , one)
print("number of two's in my_list > " , two)
print("number of three's in my_list > " , three)
print("number of dave's in my_list > " , dave)

The first one

sum(meets_condition(x) for x in my_list)

looks perfectly readable and pythonic to me.

If you prefer the second approach I'd go for

len(filter(meets_condition, my_list))

Yet another way could be:

map(meets_condition, my_list).count(True)

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)

Tags:

Python