12

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

1 Answer 1

20

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

Sign up to request clarification or add additional context in comments.

3 Comments

You might want to mention the benefit of using a generator here is that any will short-circuit and return True as soon as it finds a True value.
I suggest you add link to any documentation: docs.python.org/2/library/functions.html#any
Cool, Python suggest use the built-in functions if possible

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.