True of False

Marc Christiansen usenet at solar-empire.de
Thu Sep 27 19:45:06 CEST 2007


Casey <Caseyweb at gmail.com> wrote:
> I would recommend the OP try this:
> 
> run the (I)python shell and try the following:
> 
>>>> a = [x for x in "abcdefg"]
>>>> a
> ['a','b','c','d','e','f','g']
>>>> "c" in a
> True
>>>> "c" in a == True
> False
>>>> ("c" in a) == True
> True
> 
> The reason your conditional failed is that it was interpreted as "c"
> in (a == True) which is False.

That was my first thought, too. But watch:
  >>> a = list("abcde")
  >>> a
  ['a', 'b', 'c', 'd', 'e']
  >>> "c" in (a == True)
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  TypeError: argument of type 'bool' is not iterable

Then it dawned on me (is this the right phrase?): It's the same situation
as e.g. x < y >= 1, which means the same as "x < y and y >= 1" (except
that y is only evaluated once). So '"c" in a == True' gets evaluated as
'"c" in a and a == True'.

> the "==" operator binds at a higher precedence level than the "in"
> operator, just as multiplication binds higher than addition

Operator precedence plays no role in this case. It is a case of
'chained' comparisons.

Hope that clears it up
Marc



More information about the Python-list mailing list