How to sort a list? NOT a newbie question.

Tim Peters tim.one at home.com
Fri Sep 21 14:17:35 EDT 2001


[Grant Griffin]
> ...
> Cartesian_cmp = lambda a,b: (a.real != b.real) * cmp(a.real, b.real) + \
>                             (a.real == b.real) * cmp(a.imag, b.imag)

Why lambda?  Surely

    def Cartesian_cmp(a, b):
        if a.real == b.real:
            return cmp(a.imag, b.imag)
        else:
            return cmp(a.real, b.real)

is clearer.

Simpler is

    Cartesian_cmp = lambda a, b: cmp((a.real, a.imag), (b.real, b.imag))

That is, sequences in Python are compared lexicographically, and tuples are
a sequence type; you don't have to fake lexicographic comparison by hand.

Notes:

+ Python used to compare complex numbers that way.

+ For technical implementation reasons, it used to be impossible to
  raise an exception from a comparison function.  That's the real reason
  Python defined comparison on any pair of objects of builtin types:
  it had no choice.  User-defined __cmp__ functions could try to raise
  exceptions, but if they did such exceptions were ignored.

+ Since all comparisons used to go through __cmp__, it was impossible
  for a comparison implementation to know which specific comparison
  was desired.

+ Eventually, it became possible to raise exceptions from comparisons,
  and, later, "rich comparisons" added the ability to know which
  specific comparison was desired.  After both of those were in place,
  Guido was keen to allow complex comparisons only of the == and !=
  flavors.  Python "in his head" always worked that way; it just took
  a few years for the implementation to catch up <wink>.

channeling-is-a-vital-life-skill-ly y'rs  - tim





More information about the Python-list mailing list