Reputation: 9809
Is there a built-in function to determine if instance of a class exists in a list?
Currently I am doing it through a comprehension
>>> class A:
... pass
...
>>> l1=[5,4,3,A(),8]
>>> e=[e for e in l1 if isinstance(e,A)]
Upvotes: 12
Views: 14486
Reputation: 133514
Return
True
if any element of the iterable is true. If the iterable is empty, returnFalse
.
>>> class A(object): # subclass object for newstyle class (use them everywhere)
pass
>>> l1=[5,4,3,A(),8]
>>> any(isinstance(x, A) for x in l1)
True
By using a generator expresson
(isinstance(x, A) for x in l1)
in conjuction with any
, any
can short circuit and return True
upon finding the first True
value (unlike the list comprehension).
Upvotes: 20