about sort and dictionary

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Nov 22 16:42:59 EST 2005


On Tue, 22 Nov 2005 08:53:07 -0800, rurpy wrote:

> I am not a complete newb at python, but I am still pretty new.
> I too thought immediately that the output should be 3,2,1, 1,2,3.

What you are saying is that a.reverse() should *both* change a in place
*and* return a reference to the same list.


> I used reverse() and sort() a couple time and of course read
> the docs before I did.  I noted they do the change inplace, and
> don't find rememering that to be a terrible burden.  Actually, I
> get rather annoyed by the comment that they return None "as
> a reminder" that the change is inplace.  How arrogant!  While
> I'm sure the designers had kindly intentions. my memory, though
> bad, is not that bad, and I object to being forced to write code
> that is more clunky than need be, because the designers thought
> they needed to help me with my memory.

Built-in methods with side-effects (sort, reverse, update, clear, etc.)
return None because every function must return something, not because it
is a reminder. Python is not Pascal, and there are no procedures.

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.


-- 
Steven.




More information about the Python-list mailing list