about sort and dictionary

Steven D'Aprano steve at REMOVEMEcyber.com.au
Wed Nov 23 02:38:11 EST 2005


bonono at gmail.com wrote:

> Steven D'Aprano wrote:
> 
>>There are four possibilities for a construction like list.sort():
>>
>>(1) sort the list in place and return a reference to the same list;
>>(2) sort the list in place and return a copy of the same list;
>>(3) sort the list in place and return None;
>>(4) don't sort in place and return a sorted list.
>>
>>No solution is always right, no solution is always wrong, but the most
>>flexible is a combination of (3) and (4). Python now has that with sort()
>>and sorted(). Prior to the addition of sorted() to the language, (3) was
>>considered the best solution because of a simple Python principle: never
>>duplicate objects unless explicitly told to.
>>
> 
> I don't see the reason that (3) and (4) are the most flexible.

If you only want one copy of the data, sorted, you sort 
in place with (3).

If you want two copies of the data, one sorted and one 
not sorted, you use solution (4).

(2) fails the "don't wastefully make a copy of data if 
it isn't needed" test.

(1) is sub-optimal because it introduces a dependency 
that isn't obvious. It not only modifies the list in 
place, but it creates a new reference to the same list. 
Expect to see lots of wasteful L = L.sort() lines by 
people who forget it sorts in place. Expect to see code 
like M = L.sort(); print L; print M by people who 
forget that M and L are both the same sorted list.


> Again, "never duplicate objects unless explicitly told to" combined
> with "=" is name binding gives me a very strong message that
> list.sort() it will change things in place and which is why it is quite
> natural(for me at least)

Which is the behaviour of L.sort(). Did you think I was 
arguing against that? Heavens no -- I think sort() as 
it exists is the optimal solution. It isn't that 
difficult to say M = L[:]; M.sort() when you want a 
sorted copy.

Having said that, since sorted() now exists, I'll 
happily use it. I just don't think it is necessary.



-- 
Steven.




More information about the Python-list mailing list