Odd truth result with in and ==
On Thu, Nov 22, 2018 at 07:17:52AM +1100, Cameron Simpson wrote:
> On 21Nov2018 19:40, MRAB <python at mrabarnett.plus.com> wrote:
> >On 2018-11-21 19:18, Python wrote:
> >>>>>1 in [1,2,3] == True
> >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.
> Me either. In fact, I was as stumped as the OP. I've never really
> considered "in" as a comparison; in my mind comparisons are between
> like items: numbers vs numbers, and so forth. Not elements versus a
> collection of elements.
Well, I actually do... "in" is essentially shorthand for something
def in(item, list):
for i in list:
if i == item: # comparison
i.e. a series of comparisons.
So while I certainly didn't expect this, I do think it makes sense
after the explanation. I was, even after years of Python coding,
unfamiliar with comparison chaining. Not sure I love it, but I'll
admit that it makes sense with 1 < x < 100 comparisons, and I've
even wanted to do that on occasion. I just wasn't aware that python
actually lets you.
> Can someone show me a real world, or failing that - sane looking,
> chained comparison using "in"?
Here I'll admit that this was not my code, and I would never write
that, though I can imagine that someone might want to write something
roughly equivalent, conceptually, like:
if item in list == item_should_be_in_list():
# "good" state, i.e. is true if item is in list and should be, or isn't and shouldn't.
...though I myself would most likely never create such a construct.
So I'm not very surprised that I've never come across this before.
Mostly, I was just at a loss to explain it to someone who asked about