Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if instance present in list

Tags:

python

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)]
like image 302
IUnknown Avatar asked May 23 '13 04:05

IUnknown


1 Answers

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

like image 109
jamylak Avatar answered Oct 22 '22 13:10

jamylak