Elias Rhouzlane Elias Rhouzlane - 7 months ago 32
Python Question

Count type objects in a list

Have you a great method to count number of

in my

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

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


You can use a generator 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 did not work because the method was testing how many items in the list equaled Sugar. In other words, it was basically doing item==Sugar for each item in the list. This is incorrect because you want to be testing the type of each item, which is what isinstance does.