list.sort()

Martin von Loewis loewis at informatik.hu-berlin.de
Sun Jun 17 22:29:37 CEST 2001


"Nick Perkins" <nperkins7 at home.com> writes:

> I do find it a bit strange that list.sort() returns None, but I am sure
> there is a good reason for that.

The reason is that returning a value might trick you into believing
that you got a copy. E.g. you could write

for k in foo.sort():

and it would work alright at the surface, but it might be confusing
that the order of elements has actually changed. Returning None is
also confusing to some people, but they'll notice their error much
quicker.

In short, returning None tells you that you got a procedure, not a function.

> It is also strange that you can legally do:
> [3,2,5].sort()
[...]
> I presume that the list actually gets sorted, but since no referece is
> maintained to the list, it immediately becomes 'garbage', and is lost
> forever.

Exactly. Same issue: You might expect this to work, and it
doesn't. This is no big deal, as you'll immediately notice the problem
when running the code.

Now, some people might expect sort and reverse to return a *new*
array. That would be more expensive in many cases. Plus, changing it
*now* is not appropriate: it would break code that expects that .sort
sorts inplace, whereas a method that returns a new object would not
sort the object itself.

Regards,
Martin



More information about the Python-list mailing list