[Tutor] Puzzled by print lst.sort()

Shantanoo Mahajan shantanoo at gmail.com
Sat Sep 30 22:37:24 CEST 2006


+++ Dick Moores [30-09-06 10:47 -0700]:
| At 05:07 AM 9/30/2006, Liam Clarke wrote:
| >Dick Moores wrote:
| > > At 03:22 AM 9/30/2006, Liam Clarke wrote:
| > >> Dick Moores wrote:
| 
| > >> A Python list sort is destructive, as you can see - it has modified
| > >> lst. So, to emphasise that it is destructive, it returns None. You'll
| > >> find this in most destructive methods and functions in Python.
| > >
| > > OK, but returning the new list would seem to make more sense. Is the
| > > reason sort() doesn't, really only that it is better to emphasize that
| > > it is destructive?
| >
| >Hi Dick,
| >
| >According to the guy who runs Python, yup. Got to remember the downside
| >to destructive functions is that everything in Python is a reference.
| >For example:
| >
| >  >>> a = [3,2,1]
| >  >>> b = a
| >  >>> b.sort()
| >  >>> print a
| >[1, 2, 3]
| >
| >If you could use
| >
| >y = x.sort()
| >
| >to get a copy of the sorted list, you'd find that subtle bugs would
| >appear and frustrate you. In functional languages like Common Lisp or
| >Scheme, destructive functions are very clearly marked as such, (in
| >Scheme, they use exclamation marks - (sort! x) to indicate a destructive
| >version of (sort x).) as a key part of the functional paradigm is
| >reducing side effects.
| >
| >I believe sorting in place has performance advantages too.
| >
| >It's covered in the official FAQ:
| >
| >http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list
| 
| Thanks for the further enlightenment, Liam.

Maybe following is helpful:

>>> a=[3,2,1]
>>> b=a[:]
>>> b.sort()
>>> c=sorted(a)
>>> print a,b,c
>>> [3, 2, 1] [1, 2, 3] [1, 2, 3]
>>>

Shantanoo
-- 
The world we have created is a product of our thinking; it cannot be
changed without changing our thinking.  ~Albert Einstein


More information about the Tutor mailing list