mrmarcdee
mrmarcdee

Reputation: 21

Find if a class object is in an array/list

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

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

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

Lev Levitsky
Lev Levitsky

Reputation: 65791

any(isinstance(x, MyClass) for x in g)

Upvotes: 1

cdhowie
cdhowie

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

Related Questions