sorted (WAS: lambda)

Steven Bethard steven.bethard at
Thu Jan 13 13:28:27 EST 2005

Paul Rubin wrote:
> That completely depends on the objects in question.  Compare
>    temp = all_posters[:]
>    temp.sort()
>    top_five_posters = temp[-5:]
> to:
>    top_five_posters = all_posters.sorted()[-5:]
> which became possible only when .sorted() was added to Python 2.4.

I believe you mean "when sorted() was added to Python 2.4":

py> ['d', 'b', 'c', 'a'].sorted()
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: 'list' object has no attribute 'sorted'
py> sorted(['d', 'b', 'c', 'a'])
['a', 'b', 'c', 'd']

Note that sorted is a builtin function, not a method of a list object. 
It takes any iterable and creates a sorted list from it.  Basically the 
equivalent of:

def sorted(iterable):
     result = list(iterable)
     return result


More information about the Python-list mailing list