Dick Moores wrote: > At 03:22 AM 9/30/2006, Liam Clarke wrote: >> Dick Moores wrote: >>> >>> >>> lst = [5,3,7,6,2] >>> >>> lst.sort() >>> >>> lst >>> [2, 3, 5, 6, 7] >>> >>> lst = [5,3,7,6,2] >>> >>> print lst.sort() >>> None >>> >>> lst >>> [2, 3, 5, 6, 7] >>> >>> I'm wondering why "print lst.sort()" doesn't print the newly >>> sorted >>> list, but instead prints "None". In fact, the sorting has taken >>> place >>> because of "print lst.sort()". Is this behavior a Good Thing in >>> Python? >>> >>> Dick >>> >>> _______________________________________________ >>> Tutor maillist - >>> Tutor@python.org <mailto:Tutor@python.org> >>> >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> Hi Dick, >> >> 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? > >> However, as of Python 2.4, there's a new built-in function that has >> the functionality you want: >> >> >>> x = [3,1,2] >> >>> y = sorted(x) >> >>> print y >> [1, 2, 3] >> >>> print x >> [3, 1, 2] >> >> You'll note that sorted() is *not *destructive - that is, x is not >> modified. > > Didn't know about sorted(). Thanks, Liam. > > Dick > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor >
Oh, and PS - you'll find that list.reverse() also returns None. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor