elegent
elegent

Reputation: 4007

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?

Upvotes: 3

Views: 4200

Answers (2)

Greg Edelston
Greg Edelston

Reputation: 533

It sounds like you're asking for a filter:

count = len( filter(lambda i: isinstance(i, myClass), myList))

Upvotes: 0

khelwood
khelwood

Reputation: 59113

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)

Upvotes: 4

Related Questions