Sorting out sort (Re: Python vs. Ruby)
Anders J. Munch
andersjm at dancontrol.dk
Thu Jan 2 08:34:49 EST 2003
"Rob Renaud" <rpgnmets at aol.com> wrote in message
news:3759308d.0301011401.4b32deba at posting.google.com...
> <lot snipped>
> "John Roth" <johnroth at ameritech.net> wrote in message
> > Whether append() returns a *new* object or not is irrelevant to
> > my arguement. The fact that it returns None is the wart.
> >
> > John Roth
>
> It's consistant, not a wart from my perspective. If an object is
> modified, it is not returned.
>
> For every part of the (admittedly small) python library I know, that
> is the case. Returning None is a hint that the object is modified.
>
> So then the question becomes, why don't append(), sort(), reverse()
> return a new list and not modify the original? Are mutable objects
> themselves a wart on the langauge?
As others have answered, for performance reasons. All in all, the
design choices for list's sort method make perfect sense.
I do miss a true functional sort though. More often than not,
performance is not that critical, and a functional sort would allow
simpler, clearer code.
Fortunately it's easy to write one yourself:
def sort(sequence, cmpfunc=None):
"""sort a sequence, returning a new list; if given, cmpfunc(x,y) -> -1, 0,
1"""
sorted = list(sequence)
if cmpfunc is None:
sorted.sort()
else:
sorted.sort(cmpfunc)
return sorted
How about adding this to the library somewhere?
my-preference-would-be-as-a-builtin-ly y'rs, Anders
More information about the Python-list
mailing list