[Tutor] Re: list method sort()
Karl Pflästerer
sigurd at 12move.de
Fri Apr 2 14:03:35 EST 2004
On 2 Apr 2004, Andrei <- project5 at redrival.net wrote:
> Crabtree, Chad wrote on Fri, 2 Apr 2004 09:23:39 -0500:
>> Am I correct in my belief that sort() on lists is in place with no return
>> value? If so does any one know WHY? WHY WHY? It doesn't make sense
> Yep, but I'm not sure why. Orbitz might have a point, in that it might be
> mainly for stylistic reasons, i.e. to emphasize that the list is modified
> in-place. Think of this: what would you have liked sort() to return?
The sorted list.
> - the list itself? If you did:
> >>> myotherlist = mylist.sort()
> >>> myotherlist.append(5)
> wouldn't you be surprised to find that 5 was appended to mylist as well?
No. Since I know that append() and sort() are destructive functions.
If I wanted a copy of the sorted list I would write:
lst2 = lst.sort()[:]
> - a copy of the list? This would become way too expensive in most cases,
If I need a copy I say it explicitly. see above
> because when you sort a list, you generally want that list itself sorted,
> you don't want a sorted copy of the list.
ACK. But that's no reason to ot return the sorted list.
[...]
>> everything else returns a value istead of having crazy side affects for no
[...]
> Oh, I'll bet you know more, you just didn't think of them on the spot :).
> Operations on mutable types tend to NOT return anything. E.g. look at a
> dictionary:
>>>> d = {}
>>>> d.__setitem__(1,2) # modifies d in-place, doesn't return anything
>>>> d # demonstrate that d was modified:
> {1: 2}
Sometimes you which d got returned.
> Or the list:
>>>> mylist = []
>>>> mylist.append(4) # no return value, modifies in-place
>>>> mylist
> [4]
> It would be weird to have mylist.append() return the list, wouldn't it? It
Absolutely not. It seems to me you don't know Lisp where either append
(non-destructively) or nconc (a destructively append) return the
modified list.
Especially sort() would make sense to return a value. Imagine a list
comprehension; now you have to write to use a sorted result
res = [x for x in something if x < something_else]
res.sort()
for y in res: ...
but wouldn't it be nice to write:
for y in [x for x in something if x < something_else].sort():
IMO yes.
You can write your sort function which takes a list, calls its sort
method and returns the sorted list, like:
def nsort (lst, *args):
lst.sort(*args)
return lst
But it would be nicer as a builtin.
> would seem weird to me anyway. Yet append() is not any different from
> sort(), so having one return something and the other not, would be very
> confusing and unpredictable.
ACK. Therefore both should return the altered list.
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list