Unexpected behaviour from the 'in' operator

Carl Banks imbosol-1046063015 at aerojockey.com
Mon Feb 24 06:23:34 CET 2003

Blair Hall wrote:
> I have just noticed that the 'in' operator for lists appears to
> use the __eq__ method of a class. This does not
> provide the behaviour I expected when implementing
> an ad hoc numeric class type.
> The 'y in lst' expression evaluates to true here, because
> both x and y are equal to the same value. However,
> x and y are not the same object!  It seems to me that
> the comparison should use something like the id() function
> instead of __eq__.

Nah, if that was the case, then useful stuff like this won't work

    if s in ("hello", "goodbye"):

The language designers felt that testing logical equivalence (==) was
more important than testing object sameness (is), so that's what the
operator in does.  (I happen to agree with this; I use == far more
often than I use is.)

This can be misleading to some people who understand the difference
between == and is, because the phrase "A is in B" suggests to many
speakers (including myself) that A is the same object as an object in
B.  (Amazingly, Python has survived this minor malapropism, something
you wouldn't expect based on the PEP 308 discussion threads.)

Nevertheless, testing a list for a certain object is useful enough to
warrant a method, IMO; especially since this can be done very easily
and efficiently in C.

A simple, quick workaround to this is to use:

   id(A) in map(id,B)


More information about the Python-list mailing list