Unexpected behaviour from the 'in' operator

Terry Reedy tjreedy at udel.edu
Mon Feb 24 06:28:37 CET 2003

"Blair Hall" <b.hall at irl.cri.nz> wrote in message
news:3E599D53.97BEF0BF at irl.cri.nz...
> I have just noticed that the 'in' operator for lists appears to
> use the __eq__ method of a class.

By specification: "For the list and tuple types, x in y is true if and
only if there exists an index i such that x == y[i] is true. "  Set
membership is based on value, not artifactual inplementation ids.

>This does not provide the behaviour I expected when implementing
> an ad hoc numeric class type.

Would you really expect and be happier if '99 in [99]' were true while
'100 in [100]' were false?  (Because of current behind-the-scenes (and
changeable) implementation details.)  Should 'B' in 'Blair' be false?

>>> y=101
>>> id(x), id(y)
(7691548, 7691536)
>>> y in [x]

Why should your 'ad hoc' number type be different from builtins?  The
reason to define __eq__ method is to get comparison-by-equality
behavior.  If you do not want that, omit it and you will get the
comparison-by-id behavior you think you want.

>>> class c: pass
>>> c() in [c()]

Terry J. Reedy

More information about the Python-list mailing list