This is one of our post in the “Python function of the day” series which explains about python inbuilt functions. Today we will learn about cmp().
cmp() : The method cmp() compares two datatypes. The data types supported are strings, lists, tuples, sets, dicts, etc. If elements are of the same type, perform the compare and return the result. If elements are different types, check to see if they are numbers. If numbers, perform numeric coercion and compare. If we exhaust in comparing elements, the result is a tie, meaning that 0 is returned.

cmp() function will do below comparison in one go.

object1 < object2, if object1 is less then the result is -1
object1 > object2, if object2 is less, then the result is 1
object1 = object2, , if object1 and object2 are same then the result is 0

Python cmp() Syntax

cmp(object1, object2)

Note for python3: Python3 do not have cmp() function anymore. Use below code to implement cmp in your code.

((str1 > str2) - (str1 < str2))

Let us see some examples on cmp function

Example1: Compare two strings

>> str1='abc'
>>> str2='xyz'
>>> cmp(str1,str2)
-1

Example2: Compare two lists

>> list1=[23,45,86]
>>> list2=[98,23,23]
>>> cmp(list1,list2)
-1
>>> cmp(list2,list1)
1

Example3: compare two tuples

>> T = ('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry', 'Charles')
>>> t = ('Red', 'Purple', 'Green', 'Yellow', 'Black', 'Blue')
>>> cmp(T, t)
-1
>>> T > t
False
>>> cmp(t, T)
1
>>> t > T
True
T = (12, 56, 76, 32)
>>> t = (55, 45, 34, 99)
>>> cmp(T, t)
-1
>>> T > t
False
>>> cmp(t, T)
1
>>> t > T
True

We will see other inbuilt stuff other time.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.