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
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
Copyright © 2021 Jogjafile Inc.
You can use a generator expression with
sumandisinstance:Also,
list.countdid not work because the method was testing how many items in the list equaledSugar. In other words, it was basically doingitem==Sugarfor each item in the list. This is incorrect because you want to be testing the type of each item, which is whatisinstancedoes.