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
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.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
Anisble: ERROR! unexpected parameter type in action:
Fix- June 29, 2020
- FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018