What does the cmp() function do in Python Object Oriented Programming?

The cmp() function was a built-in function in Python 2 that compared two objects and returned an integer indicating their relationship. It has been removed in Python 3, but understanding its behavior is useful for legacy code and implementing custom comparison logic.

Syntax

cmp(x, y)

Return Values

The cmp() function returns ?

  • Negative number (-1) if x is less than y
  • Zero (0) if x is equal to y
  • Positive number (1) if x is greater than y

Basic Examples

Here are some examples showing how cmp() works with different data types ?

# Python 2 examples (cmp() removed in Python 3)
print(cmp(2, 8))    # -1 (2 < 8)
print(cmp(6, 6))    # 0  (6 == 6)
print(cmp(4, 1))    # 1  (4 > 1)
print(cmp('stackexchange', 'stackoverflow'))  # -1
-1
0
1
-1

Comparing Lists

The cmp() function can also compare lists element by element ?

# Python 2 example
list1 = [456, 'xyz']
list2 = [789, 'abc']
list3 = list2 + [896]

print(cmp(list1, list2))  # -1 (456 < 789)
print(cmp(list2, list1))  # 1  (789 > 456)
print(cmp(list2, list3))  # -1 (list2 shorter than list3)
-1
1
-1

List Comparison Rules

When comparing lists, cmp() follows these rules ?

  • Compare elements of the same type normally
  • For different types, numbers are considered "smallest"
  • Non-numeric types are sorted alphabetically by type name
  • If one list is shorter, the longer list is "larger"
  • If lists are identical, return 0

Python 3 Alternative

Since cmp() was removed in Python 3, you can implement similar functionality ?

def cmp(x, y):
    """
    Replacement for Python 2's cmp() function
    """
    return (x > y) - (x < y)

# Test the function
print(cmp(2, 8))    # -1
print(cmp(6, 6))    # 0
print(cmp(4, 1))    # 1
-1
0
1

Conclusion

The cmp() function provided a standardized way to compare objects in Python 2, returning -1, 0, or 1 based on the relationship. While removed in Python 3, its logic can be replicated using comparison operators for legacy code compatibility.

Updated on: 2026-03-24T19:42:46+05:30

606 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements