strings and sort()
Paul Rubin
phr-n2002a at nightsong.com
Wed Feb 20 22:41:31 EST 2002
"Sean 'Shaleh' Perry" <shalehperry at attbi.com> writes:
> > Why doesn't sort() return the sorted list. I would like to chain it
> > to other operations:
> > b=[x for x in a].sort()
> >
> efficiency. Why return the sequence when we usually just need to sort the
> list. Sort is also a meothod of an object, why should it return a new object
> instead of just affecting the one it belongs to?
I don't understand this reply. The sort method would be no less efficient
if it returned the sequence:
def nsort(a):
a.sort()
return a
The reason it doesn't work that way is so people don't do
a = b.sort()
expecting to get a sorted copy of b, ending up with a rude surprise
when b gets clobbered.
In Scheme, there's a convention that function names ending with "!"
operate are destructive:
(reverse x) ; makes a copy of list x, in reverse order
(reverse! x) ; reverses list x, in place
In Common Lisp, there's a similar convention that the destructive
version starts with "n":
(reverse x) ; make reverse copy of x
(nreverse x) ; reverse in place
(concat a b) ; copy and concatenate two lists, like "a+b" in Python
(nconcat a b) ; concatenate in place, like "a.extend(b)" returning a
If there was a built-in sort function, CL would use "nsort" like the
above, and "sort" as the equivalent of "a[:].nsort()" (make a
copy of a, sort the copy in place, and return the copy).
I think Python's definition of "sort" is a minor wart. It's confusing
that sort doesn't make a copy, and to ameliorate the confusion, sort
is made to not return sorted list, causing inconvenience.
I think the CL approach would have been better, to have separate
sort() and nsort() operations for sorting in place and making a copy.
Or just have nsort, whose weird-looking name alerts the user that it
has special behavior.
More information about the Python-list
mailing list