compare function in sort function of lists

Tim Peters tim.one at comcast.net
Fri Apr 5 17:59:07 EST 2002


[Gabe Newcomb]
> 	I'm trying to sort a list numerically, e.g.,  so that 11 comes
> AFTER 2.

I suspect you're sorting a list of strings, not numbers (in Python before
2.3, these will display 0 and 1 respectively):

>>> '11' > '2'
False
>>> 11 > 2
True
>>>

> The documentation says I need to pass sort() a compare
> function...but I can't find an example of this.

You don't *need* to pass a compare function, and usually shouldn't.

>>> x = ['2', '11']
>>> x.sort()
>>> x
['11', '2']
>>> y = map(int, x)  # convert the strings to integers
>>> y
[11, 2]
>>> y.sort()
>>> y
[2, 11]
>>>






More information about the Python-list mailing list