Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count type objects in a list

Have you a great method to count number of Sugar in my goblet?

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

goblet = [Sugar(), Sugar(), Milk(), Coffee()]
sugar_dosage = goblet.count(Sugar) #Doesn't work
like image 995
nestarz Avatar asked Dec 30 '25 04:12

nestarz


1 Answers

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.