3

I noticed the following strange behavior:

'a' in 'a' == True # Returns False
('a' in 'a') == True # Returns True
'a' in ('a' == True) # throws TypeError

How is the first expression parsed? Both placements of parentheses yield different results. (Python 3.6)

John
  • 935
  • 6
  • 17
  • 2
    The relevant phrase is "chained comparison"; there are lots of Q/A pairs already on the site, but it's hard to know what phrase to google first. – DSM Jul 23 '18 at 02:55
  • @BradSolomon: the first _does_ return True. But it's a chained comparison, so `'a' in 'a' == True` is exactly the same as `('a' in 'a') and ('a' == True)`, which is `True and False`, which is False. This is covered in the relevant section of the docs. – DSM Jul 23 '18 at 02:59

1 Answers1

2

From the docs:

Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.

in and == are membership and comparison operators respectively.

From Comparisons:

... expressions like a < b < c have the interpretation that is conventional in mathematics:

[...]

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358