Very basic, sorting a list ???

self.mrlimbo self.mrlimbo at gmail.com
Thu Nov 29 11:48:12 EST 2007


On 29 nov, 04:11, Hrvoje Niksic <hnik... at xemacs.org> wrote:
> Stef Mientki <S.Mientki-nos... at mailbox.kun.nl> writes:
> > although I find it rather non-intuitive.
> > I didn't expect a copy, but a reference to itself wouldn't be asked
> > too much ?
>
> If you didn't expect a copy, why rely on the return value?  You could
> simply continue using the sorted list.  Your first post says "I'm
> trying to sort a list, using the same list at the commandline works,
> but in a program it doesn't."
>
> > Why does it return None, instead of the sorted object itself ?
> > I guess it would cost almost exactly the same processing power.
>
> It's not about processing power at all, it's about clarity.  Code that
> says:
>
> foo = [5, 2, 3, 1]
> bar = foo.sort()
>
> might run into a nasty surprise upon finding that both foo and bar
> point to the same (sorted) list.  Returning None ensures that the
> error is detected as early as possible.
>
> Returning a list strongly indicates that a copy is being made.  For
> example, the following Perl code:
>
> @foo = (3, 2, 1);
> @bar = sort @foo;
>
> makes @bar sorted, but leaves @foo alone.


try
>>> foo = [5, 2, 3, 1]
>>> bar = sorted(foo)
>>> foo
[5, 2, 3, 1]
>>> bar
[1, 2, 3, 5]



More information about the Python-list mailing list