Search code examples
pythonpython-2.7python-3.xcountinstances

Count class instances in a Python list


I wonder what´s the best and fastest way to count the number of occurrences of a particular object (user-defined class instance) in a Python list?

For instance if we have a class called MyClass

class MyClass:
    """A simple example class"""
    i = 42
    def foo(self):
        return “Hello world”

and a list myList consisting of six elements:

myList = [MyClass(), MyClass(), 2, 3, 'egg', MyClass()]

we could count the number of occurrences of an object which is a MyClass instance by iterating myList and using the isinstance() function:

count = 0

for item in myList:
    if isinstance(item, MyClass):
        count += 1

But is there any better or more pythonic way to do this?


Solution

  • You can do that kind of count using sum, since True equals one and False equals zero:

    count = sum(isinstance(x, MyClass) for x in myList)