visc
visc

Reputation: 4959

Check if list contains a type?

What is the fastest way I can check for a certain types existence in a list?

I wish I could do the following:

class Generic(object)
    ... def ...
class SubclassOne(Generic)
    ... def ...
class SubclassOne(Generic)
    ... def ...

thing_one = SubclassOne()
thing_two = SubclassTwo()
list_of_stuff = [thing_one, thing_two]

if list_of_stuff.__contains__(SubclassOne):
    print "Yippie!"

EDIT: Trying to stay within the python 2.7 world. But 3.0 solutions will be ok!

Upvotes: 13

Views: 13930

Answers (2)

Adam Smith
Adam Smith

Reputation: 54173

You can use any and isinstance.

if any(isinstance(item, SubClassOne) for item in list_of_stuff):
    print "Yippie!"

Upvotes: 8

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

if any(isinstance(x, SubclassOne) for x in list_of_stuff):

Upvotes: 29

Related Questions