Count type objects in a list

Do you have a great method for counting the number Sugar

in mine goblet

?

class Sugar:pass
class Milk:pass
class Coffee:pass

goblet = [Sugar(), Sugar(), Milk(), Coffee()]
sugar_dosage = goblet.count(Sugar) #Doesn't work

      

+3


source to share


1 answer


You can use an expression with sum

and isinstance

:

sum(isinstance(x, Sugar) for x in goblet)
# or
sum(1 for x in goblet if isinstance(x, Sugar))

      



Also, list.count

doesn't work because the method was checking how many elements in the list are equal Sugar

. In other words, it basically performed item==Sugar

on every item in the list. This is not correct because you want to test the type of each element that does isinstance

.

+5


source







All Articles