Very basic, sorting a list ???

Hrvoje Niksic hniksic at xemacs.org
Thu Nov 29 05:11:18 EST 2007


Stef Mientki <S.Mientki-nospam 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.



More information about the Python-list mailing list