Are you looking to compare two objects using Python 3, but unsure how to do it? Don’t worry! In this tutorial, we’ll learn how to use the comparison function (cmp) that was available in Python 2.x versions, but is not present in Python 3. We’ll show you how to achieve the functionality of cmp using the __cmp__()
method in Python 3.
Step 1: Understand cmp
in Python 2.x
In Python 2.x, the cmp
function was used for comparing two objects. It returned -1 if the first object was less than the second object, 1 if the first object was greater than the second object, and 0 if the two objects were equal.
For example, in Python 2.x, you could do the following:
1 |
result = cmp(10, 20) |
In this example, result
would be -1, as 10 is less than 20.
Step 2: Learn the alternatives to cmp
in Python 3
In Python 3, the cmp
function has been removed. Instead, Python 3 provides three comparison operators: <
, >
, and ==
which can directly help you find if one object is less than, greater than, or equal to another object.
For example, in Python 3, you could use the following code to achieve the same functionality as the cmp
function:
1 2 3 4 5 6 7 8 9 |
a = 10 b = 20 if a < b: result = -1 elif a > b: result = 1 else: result = 0 |
In this example, result
would be -1, as the first object (a) is less than the second object (b).
Step 3: Emulate cmp
in Python 3 using a custom function
We can create a custom function, named cmp_func
, to emulate the original cmp
function in Python 3:
1 2 3 4 5 6 7 |
def cmp_func(a, b): if a < b: return -1 elif a > b: return 1 else: return 0 |
To use this cmp_func
function, you can simply pass two objects and get the comparison result:
1 |
result = cmp_func(10, 20) |
In this example, result
would be -1, as the first object (10) is less than the second object (20).
Full code:
1 2 3 4 5 6 7 8 9 10 |
def cmp_func(a, b): if a < b: return -1 elif a > b: return 1 else: return 0 result = cmp_func(10, 20) print(result) |
Output:
-1
Conclusion
Using the steps above, you can successfully emulate the cmp
function from Python 2.x in Python 3. Remember that Python 3 has removed cmp
in favor of relying on individual comparison operators like <
, >
, and ==
. But if you prefer to have a comparable function like cmp
in Python 3, you can create a custom cmp_func
as demonstrated above. Happy coding!