about sort and dictionary
rurpy at yahoo.com
rurpy at yahoo.com
Wed Nov 23 00:21:07 CET 2005
"Steven D'Aprano" <steve at REMOVETHIScyber.com.au> wrote in message
news:pan.2005.11.22.21.42.58.763662 at REMOVETHIScyber.com.au...
> 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.
Yes. I don't see a problem with this.
> > 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.
Quoting directly from the Library Reference:
"To remind you that they operate by side effect, they don't return
the sorted or reversed list."
> 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.
#2 makes no sense. I see the primary difference as inplace or
copy sort, and the return value as a secondary issue:
(1) Leave orignal list alone and sort a copy. Obviously this has
to return a reference to that copy.
(2) Sort list in place and...
(2a) Don't return anything (i.e. return None)
(2b) Return a reference to the list.
(2b) is clearly the most flexible (of the inplace options) because it
subsumes option (2a) -- if is you don't want to use the returned
refernce for stylistic reasons, then don't.
I think this is just another (admittedly minor) case of Python's
designers using Python to enforce some idea of programming
More information about the Python-list