Python cmp() Function: Use, Syntax, and Examples

Python cmp() function: In this tutorial, we will learn about the cmp() function in Python with its use, syntax, parameters, returns type, and examples. By IncludeHelp Last updated : June 24, 2023

Python cmp() function

The cmp() function is a library function in Python, it is used to compare two objects and returns the value according to the given values. It does not return 'true' or 'false' instead of 'true' / 'false', it returns negative, zero, or positive value based on the given input.

Note: The cmp() function was available in Python 2.x and it is not available in Python 3.x.

Consider the below example with sample input/output values:

Input:
num1 = 10, num2 = 20
Output:
cmp(10, 20) will return -1
because 10<20

Input:
num1 = 10, num2 = 10
Output:
cmp(10, 10) will return 0
because 10=10

Input:
num1 = 20, num2 = 10
Output:
cmp(20, 10) will return 
because 20>10

Syntax

The following is the syntax of cmp() function:

cmp(obj1, obj2)

Parameter(s):

The following are the parameter(s):

  • obj1 : The first object to be compared.
  • obj2 : The second object to be compared.

Return Value

The return type of cmp() function is <type 'int'>, it returns one of the following values.

  • 0 – If both of the objects are the same.
  • 1 – If obj1 is greater than obj2.
  • -1 – If obj1 is less than obje2.

Python cmp() Function: Example 1

In this example, we are comparing two integer values and two strings.

# Python code to demonstrate example of cmp()

# comparing integer values
print "Result of cmp(int,int)..."
print "cmp(10,20): ", cmp(10,20)
print "cmp(10,10): ", cmp(10,10)
print "cmp(20,10): ", cmp(20,10)

# comparing string values
print "Result of cmp(string,string)..."
print "cmp('ABC','PQR'): ", cmp('ABC','PQR')
print "cmp('ABC','ABC'): ", cmp('ABC','ABC')
print "cmp('PQR','ABC'): ", cmp('PQR','ABC')

Output

Result of cmp(int,int)...
cmp(10,20):  -1
cmp(10,10):  0
cmp(20,10):  1
Result of cmp(string,string)...
cmp('ABC','PQR'):  -1
cmp('ABC','ABC'):  0
cmp('PQR','ABC'):  1

Python cmp() Function: Example 2

# Python code to demonstrate example of cmp()
# Compare lists

list1 = [10, 20, 30]
list2 = [10, 20, 30]
list3 = [10, 20]

# Comparing 
print "cmp(list1, list2):", cmp(list1, list2)
print "cmp(list1, list2):", cmp(list2, list3)
print "cmp(list1, list2):", cmp(list3, list1)

Output

cmp(list1, list2): 0
cmp(list1, list2): 1
cmp(list1, list2): -1

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.