Search code examples
pythonlistclasspython-3.xinstances

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

Solution

  • 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.