Odd truth result with in and ==

MRAB python at mrabarnett.plus.com
Wed Nov 21 14:40:23 EST 2018


On 2018-11-21 19:18, Python 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?
> 
It's a chained comparison. It applies to '<', '<=', '>', '>=', '==' and 
'!=', but also to 'in', although I've never seen a chained comparison 
using 'in' in practice.

You can write:

1 <= x <= 10

which is equivalent to:

1 <= x and x <= 10

except that the 'x' part is evaluated only once (this matters if you 
have, say, a function call there).



More information about the Python-list mailing list