list.sort()

Marcin 'Qrczak' Kowalczyk qrczak at knm.org.pl
Tue Jun 19 16:34:46 EDT 2001


17 Jun 2001 22:29:37 +0200, Martin von Loewis <loewis at informatik.hu-berlin.de> pisze:

> Now, some people might expect sort and reverse to return a *new*
> array. That would be more expensive in many cases. Plus, changing it
> *now* is not appropriate: it would break code that expects that .sort
> sorts inplace, whereas a method that returns a new object would not
> sort the object itself.

#define   sort   sort or reverse

And there is a little problem in adding new functions or methods
which return a sorted copy. It's more efficient to do
    l = dict.keys()
    l.sort()
    for x in l:
than
    for x in sort(dict.keys()):
because the original list is not needed here, so making a copy is
wasteful. But the new sort function can't destroy the original in all
cases. So the new idiom would be slower in some cases which suggest
that it fits better.

The reality is that generally *three* versions of sorting are desirable:
1. return a sorted copy,
2. sort in place,
3. return a sorted copy while forgetting about the original.

The only case where one variant can optimally implement another is
2 implementing 3. Other five cases have some unnecessary overhead,
especially for reversing. It follows that it's sufficient to provide
1 and 2 in the core, and 3 can be expressed using 2.

Actually Python provides only 2. The problem is that although it's
more efficient to implement 3 by 2 than by 1, it looks nicer the
other way around, as I said above.

I'm afraid that providing all three variants is too much complexity
and confusion.

There is no perfect solution.

-- 
 __("<  Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/
 \__/
  ^^                      SYGNATURA ZASTĘPCZA
QRCZAK



More information about the Python-list mailing list