Multiple comparisons in a single statement

Chris Angelico rosuav at gmail.com
Thu Mar 12 14:08:31 EDT 2020


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.

ChrisA


More information about the Python-list mailing list