[Tutor] advanced sorting

Alan Gauld alan.gauld at btinternet.com
Wed Sep 5 09:28:55 CEST 2007

"chinni" <srikanth007m at gmail.com> wrote

> i am using a macpro version(10.4.11) and python version is "2.3.5"

Thats the problem, you need Python v2.4 to use the key= feature
of sort.

There is a way to modify sort behaviour in older versions of Python
The docs say:
The sort() method takes an optional argument specifying a
comparison function of two arguments (list items) which should return
a negative, zero or positive number depending on whether the first
argument is considered smaller than, equal to, or larger than
the second argument. Note that this slows the sorting process
down considerably;.....

As an example of using the cmpfunc argument to the sort()
method, consider sorting a list of sequences by the second
element of that list:

def mycmp(a, b):
    return cmp(a[1], b[1])


Check your v2.3.5 Library Reference docs for more details.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list