madlad
madlad

Reputation: 13

Check if there is an instance of a class in a list in python

If I have the following code

class Person:
    pass
me = Person()

people = ['john','doe',me]

What is the best way to check if there is an instance of Person in the list people?

Upvotes: 1

Views: 708

Answers (2)

Walucas
Walucas

Reputation: 2568

You can do a for loop

found=False
for element in people:
    if element == isinstance(element,Person):
        found = True
        break
print(found)

Upvotes: 0

han solo
han solo

Reputation: 6590

You could check that using isinstance like,

>>> class Person:
...   pass
...
>>> me = Person()
>>> people = ['john','doe',me]
>>> any(isinstance(x, Person) for x in people)
True

Upvotes: 3

Related Questions