Comparators in Python

Vaibhhav Khetarpal Oct 10, 2023
  1. Use the cmp Argument With the sorted() Function to Sort an Array in Python
  2. Use the functools Library to Sort an Array in Python
Comparators in Python

Comparators are predominantly utilized to compare two values of the given objects. This tutorial discusses comparators and how to use comparator functions to sort an array in Python.

Use the cmp Argument With the sorted() Function to Sort an Array in Python

This method only works in Python 2 versions and is removed in the newer versions of Python released after the version Python 3.

Earlier, the sorted() method had a cmp argument that utilized comparators to sort a given data structure.

The following code uses the cmp argument with the sorted() function to sort an array in Python 2.

def compare(a, b):
    return a[0] - b[0]


data = [(8, None), (7, None), (5, None), (4, None)]
print(sorted(data, cmp=compare))

The above code provides the following Output:

[(4, None), (5, None), (7, None), (8, None)]

Use the functools Library to Sort an Array in Python

While we can use the cmp() function provided by Python in Python 2, the function does not exist for the newer version in Python 3. The use of comparators is restricted in the newer versions of Python.

A comparator function is used to sort a given data structure along with the help of the sorted() function. In Python 3, we use a key function to carry out a custom sorting process.

Here, we use the functools.cmp_to_key() function from the functools library in order to convert the newly obsolete cmp function to a key function.

The following code uses a comparator function to sort a given data structure.

from functools import cmp_to_key


def compare(a, b):
    return a[0] - b[0]


data = [(8, None), (7, None), (5, None), (4, None)]
print(sorted(data, key=cmp_to_key(compare)))

The above code provides the following Output:

[(4, None), (5, None), (7, None), (8, None)]
Vaibhhav Khetarpal avatar Vaibhhav Khetarpal avatar

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

LinkedIn

Related Article - Python Comparator