Multiple comparisons in a single statement

John Pote johnpote at jptechnical.co.uk
Thu Mar 12 18:59:32 EDT 2020


On 12/03/2020 18:08, Chris Angelico wrote:
> On Fri, Mar 13, 2020 at 4:55 AM Stephen Tucker <stephen_tucker at sil.org> wrote:
>> A quickie (I hope!).
>>
>> I am running Python 2.7.10 (and, yes, I know, support for it has been
>> withdrawn.)
> This is the same in Python 3.
>
>> I have three tuples that have been generated separately and I want to check
>> that they are identical. all I want to do is to terminate the program and
>> report an error if all three are not identical.
>>
>> My initial attempt to do this is to use logic of the form
>>
>> if not (mytup1 == mytup2 == mytup3):
>>     raise Exception ("Tuples are not identical")
>>
>> I have tried this logic form in IDLE, and it seems to do what I want.
>>
>> Is this a reasonable way to do this, or is there a better way?
>>
> Yes absolutely! (Although, as a minor quibble, I would say "equal"
> rather than "identical" here - when you talk about identity, you're
> usually using the 'is' operator.) The meaning of chained comparisons
> is broadly equivalent to comparing the middle one against the others
> ("a==b==c" is "a==b and b==c"), which does the right thing here.
>
> It's slightly unusual to negate a query rather than using "!=", but it
> makes good sense here.

In case anyone thinks the original expr
      not (mytup1 == mytup2 == mytup3)
could be changed to
      (mytup1 != mytup2!= mytup3)
remember that applying De Morgan's theorem to the original expression 
would require the 'and' operation used in chained comparisons to change 
to an 'or' operation (Python always does the 'and' operation in chained 
comparisions). EG for simple integers instead of tuples,

 >>> not (1==1==1)
False
 >>> not (2==1==1)
True
 >>> (1!=1!=1)
False                          correct as before
 >>> (2!=1!=1)
False                          oops!

John

>
> ChrisA


More information about the Python-list mailing list