osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Odd truth result with in and ==


On Thu, Nov 22, 2018 at 06:33:54AM +1100, Chris Angelico wrote:
> On Thu, Nov 22, 2018 at 6:23 AM Python <python at bladeshadow.org> wrote:
> > 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 :)

Not assuming, just asking the question, FWIW...
> 
> 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

That's kind of cool, but also a bit mind-breaking, if you're generally
familiar with how other languages evaluate expressions, but not aware
of this feature of Python. [Hi!]  It's less clear this is useful with
"in" but since python considers it a comparison operator, it's at
least consistent, which is good.
 
> 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 :)

The "redundant" comparison is not the reason for the confusion...  I
wasn't familiar with chaining comparisons.  I imagine it should be
obvious that this was a simplified example constructed to illustrate
the problem most simply, rather than real code.  After all, a
comparison between two hard-coded constant-value expressions need
never be evaluated, since the value is itself known and constant.

Thanks for the explanation.