Python functools.cmp_to_key Function

The functools.cmp_to_key function in Python's functools module converts a comparison function into a key function. This can be useful when you need to sort data using a comparison function, which was the method used in Python 2, and need to adapt it to Python 3's key-based sorting.

Table of Contents

  1. Introduction
  2. functools.cmp_to_key Function Syntax
  3. Examples
    • Basic Usage
    • Custom Comparison Function
    • Sorting with cmp_to_key
  4. Real-World Use Case
  5. Conclusion

Introduction

In Python 2, sorting was often done using a comparison function (cmp). Python 3 replaced this with a key-based approach. The functools.cmp_to_key function allows you to convert old-style comparison functions to key functions, making it easier to migrate code from Python 2 to Python 3.

functools.cmp_to_key Function Syntax

Here is how you use the functools.cmp_to_key function:

import functools

key_func = functools.cmp_to_key(cmp_func)

Parameters:

  • cmp_func: The old-style comparison function that takes two arguments and returns a negative, zero, or positive number based on their order.

Returns:

  • A key function that can be used with sorting functions.

Examples

Basic Usage

Convert a simple comparison function to a key function.

Example

import functools

def compare(x, y):
    return x - y

key_func = functools.cmp_to_key(compare)

data = [5, 2, 9, 1, 5, 6]
sorted_data = sorted(data, key=key_func)

print(sorted_data)

Output:

[1, 2, 5, 5, 6, 9]

Custom Comparison Function

Use a custom comparison function to sort strings by length.

Example

import functools

def compare_lengths(x, y):
    return len(x) - len(y)

key_func = functools.cmp_to_key(compare_lengths)

data = ["apple", "banana", "cherry", "date"]
sorted_data = sorted(data, key=key_func)

print(sorted_data)

Output:

['date', 'apple', 'banana', 'cherry']

Sorting with cmp_to_key

Sort tuples based on the second element using a comparison function.

Example

import functools

def compare_second(x, y):
    return x[1] - y[1]

key_func = functools.cmp_to_key(compare_second)

data = [(1, 3), (4, 1), (5, 2), (2, 4)]
sorted_data = sorted(data, key=key_func)

print(sorted_data)

Output:

[(4, 1), (5, 2), (1, 3), (2, 4)]

Real-World Use Case

Migrating Legacy Code

Convert an old-style comparison function to a key function for sorting a list of custom objects.

Example

import functools

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"{self.name} ({self.age})"

def compare_ages(x, y):
    return x.age - y.age

key_func = functools.cmp_to_key(compare_ages)

people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)]
sorted_people = sorted(people, key=key_func)

print(sorted_people)

Output:

[Bob (25), Alice (30), Charlie (35)]

Conclusion

The functools.cmp_to_key function is used for converting old-style comparison functions to key functions, facilitating the transition from Python 2 to Python 3. It allows you to leverage existing comparison logic in sorting operations, ensuring compatibility and ease of migration. Proper usage can enhance the readability and maintainability of your sorting code.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare