-3

I have a list that I am appending different objects to.

How would I find the total number of instances of a specific class within that list please?

1 Answers1

1
print(sum([1 for x in llist if isinstance(x, my_class)]))
Trolldejo
  • 466
  • 1
  • 7
  • 20
  • 2
    you need double equal signs to check equality `==`. And I would go with `isinstance()` like `isinstance(x, my_class)` – Ma0 May 15 '17 at 12:58
  • could you justify how isinstance(x, my_class) might be a better option than the usage of type() == ? – Trolldejo May 15 '17 at 16:06
  • This is a fair question.. I have only used (and saw used) `type` only to check against *variable types* (which are also classes) but never to check for custom classes (user-defined ones). So it is more a matter or what my eye and probably many other eyes are used to seeing. – Ma0 May 15 '17 at 16:11
  • It appears that [Python documentation](https://docs.python.org/2/library/functions.html?highlight=type#type) recommend the use of isinstance() – Trolldejo May 15 '17 at 16:15
  • [`type` vs `isinstance`](http://stackoverflow.com/questions/21894575/isinstancefoo-bar-vs-typefoo-is-bar) or better yet [this](http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python) – Ma0 May 15 '17 at 16:19