Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if list contains a type?

Tags:

python

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!

like image 566
visc Avatar asked Sep 21 '15 22:09

visc


People also ask

How do you check a list type?

Use isinstance() to check if an object has type list. Call isinstance(object, class_or_tuple) with class_or_tuple as list to return True if object is an instance or subclass of list and False if otherwise.

How do you check if a list contains a string?

if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));

How do you check if a list contains an item?

To check if the item exists in the list, use Python “in operator”. For example, we can use the “in” operator with the if condition, and if the item exists in the list, then the condition returns True, and if not, then it returns False.


1 Answers

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

like image 177
Peter DeGlopper Avatar answered Oct 17 '22 03:10

Peter DeGlopper