[Tutor] Re: Re: list method sort()

Andrei project5 at redrival.net
Fri Apr 2 15:08:37 EST 2004


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).

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.




More information about the Tutor mailing list