IUnknown
IUnknown

Reputation: 9809

check if instance present in list

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

Answers (1)

jamylak
jamylak

Reputation: 133514

any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False.

>>> 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

Related Questions