How to sort a list? NOT a newbie question.

David Bolen db3l at fitlinxx.com
Mon Sep 17 20:31:34 CEST 2001


"Ken Seehof" <kseehof at neuralintegrator.com> writes:

> Obviously the policy of python is that all things are sortable.  I really
> can't imagine how complex numbers got left out.

Actually, everything being sortable really hasn't been true ever since
objects could implement their own __cmp__ mechanisms (back in 1.5 I
think), and thus any object can raise an exception during sorting.  I
do think it's true that complex numbers are the only built-in types
that aren't comparable however, as of 2.1.

It doesn't seem like it would be terribly hard to wrap your own class
around a complex number and implement __cmp__ if you wanted to create
your own definition for comparing complex numbers.  The uncertainty as
to the "best" manner in which to compare two such numbers was at least
part of the reason for leaving it out of the core implementation, but
that doesn't prevent anyone from implementing their own approach.

This change occurred during Python 2.1 (I believe) along with rich
comparisons.  The argument at the time was the lack of mathematical
meaning in comparing complex numbers (which isn't in my area to
judge), but I think that was more along the lines of justifying the
behavior than forcing the change.

But the most logical argument against such a change I've tended to see
since is in fact the case brought up here - being able to sort lists
with complex numbers in them, or just in general being able to sort
arbitrary, heterogeneous lists.  But the latter isn't true in general
anyway (as above), and the former can be solved with a private class
implementing an acceptable comparison for the particular application
domain in question.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list