Odd truth result with in and ==

Chris Angelico rosuav at gmail.com
Wed Nov 21 14:33:54 EST 2018


On Thu, Nov 22, 2018 at 6:23 AM Python <python at bladeshadow.org> wrote:
>
> $ python3
> Python 3.5.2 (default, Nov 23 2017, 16:37:01)
> [GCC 5.4.0 20160609] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> 1 in [1,2,3] == True
> False
> >>> 1 in ([1,2,3] == True)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: argument of type 'bool' is not iterable
> >>> (1 in [1,2,3]) == True
> True
>
> How is the first not equivalent to either one of the second or third?
> My expectation is it should produce the same result as the second.  It
> *seems* like Python is ignoring the '1 in' part and just giving the
> result for '[1,2,3] == True'...  Is this just a bug?
>

Don't jump to assume it's a bug, because that kind of bug is extremely
unlikely compared to a misunderstanding :)

In Python, chained comparisons behave as if the middle term is shared.
A common and useful example is:

1 < x < 10
1 < x and x < 10

apart from the fact that x is only evaluated once. It's not common to
use "in" and "==" in this way, but it's perfectly legal. What you
wrote is equivalent to:

1 in [1, 2, 3] and [1, 2, 3] == True

which should explain the result you got. It's only confusing because
you added a redundant "== True" to the end of an otherwise simple
comparison :)

ChrisA



More information about the Python-list mailing list