can't sort

John Roth johnroth at ameritech.net
Sat May 17 14:24:48 EDT 2003


"Helmut Jarausch" <jarausch at skynet.be> wrote in message
news:3ec61600$0$11142$ba620e4c at reader0.news.skynet.be...
> Sorry for this question,
> but I am just puzzled.
>
> Why does
>
> print [4,1,3,2].sort()
>
> just print
> None
> ?
>
> As far as I understood the docs 'sort'
> should take 'cmp' for comparisons which is
> well defined for integers.
>
> Thanks for a hint,

I think the other responses have covered what happens
quite well. The question that hasn't been covered yet
is why. [].sort() returns None because it violates one of
the basic expectations: functions won't modify their
caller.

The basic fact is that [].sort(), [].reverse() and [].append()
are optimized to modify their callers rather than return a
new object. Guido chose to make those functions return
None to insure that people didn't fall into the opposite trap:
assuming that it returned a new object and then being
surprised when the original object was modified when they
didn't expect it.

I think Ruby handles this situation better than Python,
frankly. According to reports, Ruby has two methods that
correspond to [].sort(). One is [].sort(), and the other is
[].sort!(). (Note the !). The first returns what you would
naturally expect: a new object without modifying the original
object. The second returns the original object after modifying
it.

So far, this doesn't seem to have gotten high enough on
anyone's irritation list for them to have suggested a solution
that's both Pythonic and backward compatible.

John Roth


>
> Helmut Jarausch
>
> Lehrstuhl fuer Numerische Mathematik
> RWTH - Aachen University
> D 52056 Aachen, Germany
>






More information about the Python-list mailing list