# How can I use cmp(a,b) with Python3?

I was told that using the cmp function can be very useful in code-golf. But unfortunately, Python 3 doesn't have a cmp function.

So what's the shortest equivalent of cmp that works in python 3?

• You should clarify that you are looking for cmp or an alternative in the context of golfing. Otherwise, this might get closed as a general programming question very quickly. – Martin Ender May 7 '15 at 20:10
• @MartinBüttner I think this is in context of the OP's golf advice question where an answer used cmp though the question asked for Python 3. – xnor May 7 '15 at 20:15
• @xnor I know it is, but others might not. – Martin Ender May 7 '15 at 20:29
• If it is helpful to know, you can use cmp(a,b) in Python 2. – mbomb007 May 7 '15 at 22:03

Python 3 does not have cmp. For golfing, you can do

11 chars

(a>b)-(a<b)


which loses 3 chars over cmp(a,b).

Amusingly, this is also an "official" workaround. The What's New in Python 3 page says "(If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)"

• beware precedence problems! the actual equivalent of cmp(a,b) is ((a > b) - (a < b)) – Sparr May 7 '15 at 20:16
• if a or b are more complex expressions - say calls to functions with very long running times, then this is very bad for your running time. Worse, if a or b contains a call to a function with side-effects, this can even change the semantic of your program. – Algoman May 9 '18 at 10:00
• @Algoman Oh noes, running time, the most important part of code-golfing /s. If you want to avoid running functions twice, just assign them to variables beforehand (which you're probably going to end up doing anyway to save on bytes) – Jo King Oct 30 '18 at 11:17
• I'm working on a transpiler - it reads an expression and is supposed to generate an expression out of it. That cmp in the original expression could be nested deeply. it would be very ugly and hard (if not impossible) to implement, if I were to generate the target-code like that. – Algoman Oct 30 '18 at 23:04
• @Algoman So replace cmp(exp1,exp2) with (lambda a,b:(a>b)-(a<b))(exp1,exp2). – Anders Kaseorg Oct 31 '18 at 18:24