2

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

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

use a generator expression for short-circuiting : Foo in (type(x) for x in g)
1
any(isinstance(x, MyClass) for x in g)

Comments

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.