[Python Wpg] sort vs. sorted

Stuart Williams stuartw at mts.net
Fri Apr 28 08:09:59 EDT 2006


On Wednesday some of us were confused by sort vs. sorted, and
specifically why the sorted() method isn't found in a list:

>>> alist = [1, 3, 2]
>>> alist.sort()
>>> alist
[1, 2, 3]
>>> alist.sorted()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'list' object has no attribute 'sorted'
>>> alist = [1, 3, 2]
>>> sorted(alist)
[1, 2, 3]

sort() is a method of list.  As explained, it sorts the list in place
and it does not return the list as a reminder of that fact.

sorted() is a builtin function, not a method on list, because it's
more general taking any iterator as its first argument (for example an
open file), not just a list.  It of course does return a list.

Stuart.





More information about the Winnipeg mailing list