Fix Python – Custom Python list sorting


Asked By – Lorenzo

I was refactoring some old code of mine and came across of this:


def cmp_items(a, b):
    if >
        return 1
    elif ==
        return 0
        return -1

The code works (and I wrote it some 3 years ago!) but I cannot find this thing documented anywhere in the Python docs and everybody uses sorted() to implement custom sorting. Can someone explain why this works?

Now we will see solution for issue: Custom Python list sorting


It’s documented here.

The sort() method takes optional arguments for controlling the

cmp specifies a custom 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: cmp=lambda x,y:
cmp(x.lower(), y.lower()). The default value is None.

This question is answered By – miles82

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0