Fix Python – How to use a custom comparison function in Python 3?


Asked By – YOU

In Python 2.x, I could pass custom function to sorted and .sort functions

>>> x=['kar','htar','har','ar']
>>> sorted(x)
['ar', 'har', 'htar', 'kar']
>>> sorted(x,cmp=customsort)
['kar', 'htar', 'har', 'ar']

Because, in My language, consonents are comes with this order


But In Python 3.x, looks like I could not pass cmp keyword

>>> sorted(x,cmp=customsort)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'cmp' is an invalid keyword argument for this function

Is there any alternatives or should I write my own sorted function too?

Note: I simplified by using “k”, “kh”, etc. Actual characters are Unicodes and even more complicated, sometimes there is vowels comes before and after consonents, I’ve done custom comparison function, So that part is ok. Only the problem is I could not pass my custom comparison function to sorted or .sort

Now we will see solution for issue: How to use a custom comparison function in Python 3?


Use the key argument (and follow the recipe on how to convert your old cmp function to a key function).

functools has a function cmp_to_key mentioned at

This question is answered By – Tim Pietzcker

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