[Tutor] Re: list method sort()

Andrei project5 at redrival.net
Fri Apr 2 12:46:31 EST 2004


Crabtree, Chad wrote on Fri, 2 Apr 2004 09:23:39 -0500:

> Am I correct in my belief that sort() on lists is in place with no return
> value?  If so does any one know WHY? WHY WHY?  It doesn't make sense

Yep, but I'm not sure why. Orbitz might have a point, in that it might be
mainly for stylistic reasons, i.e. to emphasize that the list is modified
in-place. Think of this: what would you have liked sort() to return? 

- the list itself? If you did:
  >>> myotherlist = mylist.sort()
  >>> myotherlist.append(5)
  wouldn't you be surprised to find that 5 was appended to mylist as well?

- a copy of the list? This would become way too expensive in most cases,
because when you sort a list, you generally want that list itself sorted,
you don't want a sorted copy of the list.

- a deepcopy of the list? This is even more expensive than a shallow copy.

> everything else returns a value istead of having crazy side affects for no

Keep in mind that most of 'everything else' (e.g. tuples, strings,
booleans, integers) can simply not be changed in-place (unlike lists). This
means that any operations on these types  either returns a value, or
nothing happens since these types can't be changed in-place. 

> dicernable reason.  The only other one like this that I know of is 'del'

Oh, I'll bet you know more, you just didn't think of them on the spot :).
Operations on mutable types tend to NOT return anything. E.g. look at a
dictionary:

>>> d = {}
>>> d.__setitem__(1,2) # modifies d in-place, doesn't return anything
>>> d # demonstrate that d was modified:
{1: 2}

Or the list:

>>> mylist = []
>>> mylist.append(4) # no return value, modifies in-place
>>> mylist
[4]

It would be weird to have mylist.append() return the list, wouldn't it? It
would seem weird to me anyway. Yet append() is not any different from
sort(), so having one return something and the other not, would be very
confusing and unpredictable.

> which I've read is not technicly a function.

It's a statement (like e.g. print, global or pass). Obviously it has no
return value (neither does print for examle).

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.




More information about the Tutor mailing list