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 7:47 AM Python <python at bladeshadow.org> wrote:
>
> 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
> > >>False
> > >>
> > >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
> like:
>
>   def in(item, list):
>     for i in list:
>       if i == item:  # comparison
>         return true
>     return false
>
> i.e. a series of comparisons.
>

More or less. There are some subtleties (for instance, the check is
usually "if i is item or i == item"), and not all containers do it by
iteration (a dictionary will directly grab the item in question as a
fast check), but broadly speaking, that is correct.

>   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.
>     ...

If I saw this in _any_ language, I would want it to be parenthesized
for clarity. This kind of comparison is extremely unusual, and
benefits from not making assumptions about how comparisons chain. And
parenthesized, it will work the same way in any language.

ChrisA