Reputation: 21
If I have an array of
g = ['hi']
Then
'hi' in g
returns True
.
What if I put an instantiated class into an array.
g.append(MyClass())
How do I find if the array contains an object of this class.
MyClass in g
returns False
Upvotes: 2
Views: 290
Reputation: 250891
use isinstance()
and any()
:
In [95]: class A:pass
In [96]: lis=[A()]
In [97]: any(isinstance(x,A) for x in lis)
Out[97]: True
In [98]: lis=[1,2,3]
In [99]: any(isinstance(x,A) for x in lis)
Out[99]: False
Upvotes: 3
Reputation: 168988
Try this:
MyClass in [type(x) for x in g]
This will only find objects whose exact type is MyClass
; it will not find objects of a class derived from MyClass
. To do that, try one of the other answers that makes use of isinstance()
.
Example:
>>> class Foo(object): pass
...
>>> g = [1, 2, Foo(), 4]
>>> g
[1, 2, <__main__.Foo object at 0x7f59552ef750>, 4]
>>> Foo in [type(x) for x in g]
True
Upvotes: 1