Python List – cmp() Method: A Complete Guide 

The cmp() function was a built-in comparison method in Python 2 used to compare two values and determine their relative order. Although removed in Python 3, understanding cmp() is helpful when working with legacy Python 2 code or learning Python’s historical evolution.

1. What is the sort() method in Python?

The cmp() function compares two values and returns an integer indicating their relationship:

  • -1 → First value is less than the second
  • 0 → Both values are equal
  • 1 → First value is greater than the second
  • Important: This function does not exist in Python 3, but similar comparisons can be achieved using standard operators (<, >, ==) or custom functions.

2. Purpose of the Python sort() Method

The sort() method plays an important role when working with list data in Python. Its main goal is to help organize list items efficiently so that the data becomes easier to read, filter, process, or analyze. Because it rearranges elements directly within the same list, it is both memory-efficient and fast.

  • Organizes data for easy analysis – Sorting numbers, strings, or complex objects makes patterns more visible and helps in tasks like ranking, filtering, or grouping.
  • Improves readability – A sorted list is much easier to understand, especially when displaying results or building reports.
  • Supports custom sorting – With the key parameter, the method can sort using custom rules, such as string length, dictionary values, or tuple positions.
  • Enables descending sorting – The optional reverse=True parameter allows sorting from highest to lowest when needed.
  • Enhances performance – Since sort() works in-place, it avoids creating extra copies of lists, making it suitable for large datasets.

3. Syntax of Python cmp() Method


cmp(x, y)

4. Parameter Description

Parameter Description
x First object/value for comparison
y Second object/value for comparison

5. Return Values

Return Value Meaning
-1 x < y
0 x == y
1 x > y

6. Python reverse() Method: How It Worked

  • cmp() evaluated two values and returned a single integer (-1, 0, or 1) depending on the comparison.
  • Useful for custom sorting or ordering logic in Python 2.
  • Could compare numbers, strings, or other comparable objects.
  • In Python 3, the same effect can be achieved using:
  • 
    

    def cmp(x, y): return (x > y) - (x < y)

    This replicates the behavior of the legacy cmp() function.

6. Python cmp() Method : Practical Examples

Example 1: Comparing Integers


print(cmp(3, 7)) print(cmp(7, 3)) print(cmp(5, 5)) #Output -1 1 0

Explanation:

  1. cmp(3, 7) → 3 is less than 7 → returns -1.
  2. cmp(7, 3) → 7 is greater than 3 → returns 1.
  3. cmp(5, 5) → both numbers are equal → returns 0.

Simple numeric comparisons showing how cmp indicates relative order.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top