Count type objects in a list
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 to share