cmp to key

suggest change

Python changed its sorting methods to accept a key function. Those functions take a value and return a key which is used to sort the items.

Old comparison functions used to take two values and return -1, 0, or +1 if the first argument is smaller than, equal to, or greater than the second argument respectively. This is incompatible with the new key function.

That’s where functools.cmp_to_key comes in:

>>> import functools
>>> import locale
>>> sorted(["A", "S", "F", "D"], key=functools.cmp_to_key(locale.strcoll))
['A', 'D', 'F', 'S']

Example taken and adapted from the Python Standard Library Documentation.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents