0

I found that the result of evaluating a in b == c is always equal to (a in b) and (b == c). Could anyone explain that?

Here is an example running on Python3.7:

>>>> "123" in "1234" == "1234"
True

>>>> "123" in "1234" != "1234"
False

>>>> "123" in "1234" != "12345"
True

>>>> "123" in "1234" == "12345"
False

>>>> "888" in "1234" == "1234"
False

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
K.Q D
  • 1
  • 2
  • 1
    It works exactly the same as `1 < 2 < 3`. – Selcuk Mar 24 '21 at 04:11
  • @Selcuk the putative dupe is a laughably horrendously bad fit for this question. – hobbs Mar 24 '21 at 04:12
  • @hobbs I disagree. The question confirms the findings of this one, and the answer explains how it works internally. I am happy to add another duplicate to the list of duplicates if you suggest one though. – Selcuk Mar 24 '21 at 04:14
  • Nice question. I hadn't appreciated how weird chaining can get! – Greg Ball Mar 24 '21 at 04:25
  • The 1st dupe was not perfect, I added another one, which isn't perfect either. But there is no clear canonical dupe. I would even consider reopening this in case someone can answer it well, that would help the community I think and we can refer back to it. – jamylak Mar 24 '21 at 04:27
  • @jamylak I had been writing it :) – hobbs Mar 24 '21 at 04:35
  • @hobbs I'll just reopen it, don't see any harm in that – jamylak Mar 24 '21 at 23:09
  • 1
    Why are those expressions equivalent? Because the Python language designers decided they would be. There's not much more to it than that. – kaya3 Mar 24 '21 at 23:15
  • The `and` isn't explicitly added, the `in`, `==` and `!=` are evaluated left to right https://docs.python.org/3/reference/expressions.html#operator-precedence – OneCricketeer Mar 24 '21 at 23:17
  • The relevant section of the docs is this: https://docs.python.org/3/reference/expressions.html#comparisons – kaya3 Mar 24 '21 at 23:21
  • @jamylak: I added new dupes, pretty sure the first two are basically perfect (even combining the same two operators). – ShadowRanger Mar 24 '21 at 23:27
  • @ShadowRanger Feel free to close it again if you see fit, I see your point, I just thought that there wasn't 1 big detailed answer that got enough attention, but yes the first two do answer it – jamylak Mar 24 '21 at 23:35

1 Answers1

1

Comparisons

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

Where in is also a comparison operator

Also refer section on operator precedence to see that in and equality checks occur at the same time, left to right

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245