cmp of multiple attributes

Alex Martelli aleaxit at yahoo.com
Wed Dec 22 20:38:44 CET 2004


Steven Bethard <steven.bethard at gmail.com> wrote:

> Alex Martelli wrote:
> > Comparisons of tuples, lists, etc, are *lexicographical*: the first
> > items are compared; iff they're equal, then the second items, and so
> > forth.  IOW, exactly what you want in this case.
> 
> Just to check my understanding, this means that:
> 
>      cmp(a0, b0) or cmp(a1, b1) or ... or cmp(aN, bN)
> 
> should give the same result as:
> 
>      cmp((a0, a1, ... aN), (b0, b1, ... bN))
> 
> right?

Yes, including 'shortcircuiting' the same way (you can check by having
some ai define a __cmp__ which prints out some line of trace info).  The
single-cmp case is more general (since it also works for tuples of
unequal length -- a shorter tuple being smaller, all other things being
equal) and I suspect often speedier (but one would have to timeit for a
few cases to check), but semantically they're the same.


Alex



More information about the Python-list mailing list