Alex
Alex

Reputation: 3267

Checking membership in python list trouble

I encountered problem with item membership in list, which I can't understand. While checking is some object instance in list( with simple "item in list" ) it returns me False even if the instance is in list. Then I notice that same pointers have no same Id.

Do I have to use some special method or what? Can anybody helps me to compare instance equality, please.

NOTE: All that occasion happens in PySide if it matters.

Upvotes: 1

Views: 81

Answers (1)

root
root

Reputation: 80406

Your objects need to have an __eq__ method to define how to compare objects for equality.

In [18]: class A(object):
    ...:     def __init__(self, n):
    ...:         self.n = n
    ...:    

In [19]: class B(object):
    ...:     def __init__(self, n):
    ...:         self.n = n
    ...:     def __eq__(self, other):
    ...:         return self.n == other
    ...:     

In [20]: a = A(1) 

In [21]: b = B(1)

In [22]: a in [A(n) for n in range(10)]
Out[22]: False

In [23]: b in [B(n) for n in range(10)]
Out[23]: True

In [24]: b in [B(n) for n in range(10, 20)]
Out[24]: False

Upvotes: 1

Related Questions