Multiple comparisons in a single statement

MRAB python at mrabarnett.plus.com
Thu Mar 12 14:21:40 EDT 2020


On 2020-03-12 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.
> 
There's also the question of whether you consider, say, the int value 0 
to be identical to the float value 0.0. Equal? Yes. Identical? Depends 
what you mean by "identical".

> It's slightly unusual to negate a query rather than using "!=", but it
> makes good sense here.
> 


More information about the Python-list mailing list