[Tutor] Re: Re: list method sort()
Lloyd Kvam
pythonTutor at venix.com
Fri Apr 2 16:17:57 EST 2004
http://www.python.org/dev/doc/devel/whatsnew/node5.html
A sorted builtin will be available in 2.4. It returns a copy of the
sorted list. It's actually sorts any iterable, not just lists.
On Fri, 2004-04-02 at 15:08, Andrei wrote:
> Karl Pflästerer wrote on Fri, 02 Apr 2004 21:03:35 +0200:
>
> > No. Since I know that append() and sort() are destructive functions.
> > If I wanted a copy of the sorted list I would write:
> <snip>
>
> Well, yes, you can argue that *all* operations which modify in-place should
> return the modified object as well - I don't know if this would be better
> or not: I certainly see the advantages in some cases. My post was referring
> to inconsistent behavior (some operations returning, other ones not).
>
> >> 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.
>
> No, I haven't found Lisp attractive enough to study it. Can't say I've
> missed the feature in Python, though I have occasionally wished sort() did
> return the list. But I'd rather have consistent behavior than special sorts
> of behavior.
>
> > 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.
>
> IMO in this particular case not, simply because the first option is clearer
> than the second one. I would however be tempted to write:
>
> for y in res.sort():
>
> > You can write your sort function which takes a list, calls its sort
> > method and returns the sorted list, like:
>
> Sounds like a good idea to me :).
>
> >> 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.
>
> So how would you handle the pop-like methods then? They're destructive,
> they *must* return the item which was popped, but they should also return
> the modified list/dict (for the sake of consistency).
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-653-8139
fax: 801-459-9582
More information about the Tutor
mailing list