This "comparative" function that you encounter is incompatible: it must provide a certain (deterministic) order, that is, if you change the order of the items in the list and run sorted , you should get the same result!
In your case, the order of the elements affects the sorting:
import functools def my_cmp(x, y): return x*5-y*2 l = [50, 2, 1, 9] print(sorted(l, key=functools.cmp_to_key(my_cmp)))
which means your comparison function is incompatible. Provide a good ordering function first, so converting it to a key function is not very difficult.
Answering the question that you raised in the comments, key accepts a function that takes only one argument and returns a "dimension" of "how big it is." The simplest example is to compare numbers, in which case your key function might be simple: lambda x: x . For any number, the lambda expression will return itself, and the comparison is now trivial!
Change your example:
def my_key(x): return xl = [50, 2, 1, 9] print(sorted(l, key=my_key))
Shorter version above:
l = [50, 2, 1, 9] print(sorted(l, key=lambda x: x))
source share