Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

suppose I have a custom function such as

def greater(a, b):
    if (a % b) % 2 == 0:
        return 1
    return 0

It defines how to compare two numbers and determine which is greater. In this case, if the function returns 1 a > b else, a < b. Can I use inbuilt <built-in function sorted> orto create a sorted array of numbers with respect to this definition?

share|improve this question
up vote 2 down vote accepted

If you're using Python 2.x, then that's easily achievable by using cmp, although you have to modify your function to return -1 instead of 0. Something like this:

def greater(a, b):
    if (a % b) % 2 == 0:
        return 1
    return -1

x = [2,7,5,10,30,15]

print(sorted(x, cmp=greater))

But if you're using Python 3.x, then it gets a bit more complicated since cmp was removed. My best idea is to implement a class to hold the number and override the comparison operators __lt__ (less than) and __gt__ (greater than). Something like this:

class my_int(int):
    def __lt__(a,b):
        return (a % b) % 2 != 0
    def __gt__(a,b):        
        return (a % b) % 2 == 0

x = [my_int(2),my_int(7),my_int(5),my_int(10),my_int(30),my_int(15)]

print (sorted(x))
share|improve this answer
this is exactly what I was looking for! thanks I"m using python 2.7.2 – user5198 Jun 1 '12 at 0:40
I still can't believe removal of cmp was deemed a good idea for 3.x... – Izkata Jun 1 '12 at 2:19
@Izkata - Yeah a lot of the stuff done in the name of the all powerful Pythonic "only one way of doing things" just don't make sense to me. – System Down Jun 1 '12 at 4:13
python3.2+ has functools.cmp_to_key which essentially defines that class for you given the cmp function. So you can do sorted(x, key=cmp_to_key(greater)) – zstewart Oct 27 '15 at 19:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.