Reputation: 4007
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
Reputation: 533
It sounds like you're asking for a filter
:
count = len( filter(lambda i: isinstance(i, myClass), myList))
Upvotes: 0