How to use the cmp() function in Python 3?

cmp() function in Python 3

Is the cmp() function available in Python 3? No, the function has been removed and is not a available as built-in function anymore. If you assume cmp() is a built-in function and just call it a NameError exception is raised. NameError: name 'c' is not defined

Why was cmp() removed in Python 3?

Why is cmp() not available in Python 3 by default? It was removed to simplify the rules for ordering comparisons.
The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)

How to use cmp() in Python3?

The best solution is to define the function yourself. This is simple and straightforward and we can use the removed code: (a > b) - (a < b). def cmp(a, b): return (a > b) - (a < b) After defining our own cmp() function we can use it as usual by calling it with our arguments. a = [1,2,3] b = [1,2,3] c = cmp(a,b) print (c) The result is returned. 0


If you need the cmp() function, define it yourself in Python 3. It is the only way to use it.



Click to jump to section