cmp() Function in Python5 Jan 2025 | 5 min read The cmp() function in Python compares two objects and returns their values. It was a built-in function in Python 2. However, in Python 3, it has been replaced by == and is operators, which make comparison objects more robust, accurate, and flexible and return negative and positive values, and zero occurs based on comparison values. Let's find out more about that. ![]() If the first integer is less than the second integer, the output will be -1. Similarly, if the first object is greater than the second, the result will be 1. If both objects are the same, the output will be 0. Let us understand the concept of this cmp() method using relevant examples. Syntax Parameters Suppose x and y are the two objects in which the comparison is made. The objects can be of any data type, such as numbers or strings. Returning Values After comparing two numbers, it returns:
Some Examples to Compare Two IntegersIn the following section, we will look at some examples demonstrating the method of comparing two integers in Python. Example 1: Output -1 0 1 Explanation In the above code, the code compares two object's values using the `cmp()` method: In the first scenario, if x is less than y, the result will be -1. In the second scenario, if the comparison of x is equal to y, it prints 0. In the third scenario, compare if x is greater than y: output will be 1. Example 2: Output: 5 is less than 10 12 is equal to 12 20 is greater than 18 Explanation: We created a comp_num() function in the abovementioned program to compare two numbers. The first statement compares 5 and 10 and displays the output. The second statement compares 12 and 12 and prints the value. For the third and last call, it compares 20 and 18 and generates the result. Check if the Number is Even or Odd using cmp()In the following section, we will discuss how to check if the number is even or odd with the help of the cmp() method. Example 1: Output: Even Odd Explanation: In the first case, n%2 equals 0, indicating it's even. The cmp() function compares 0 with the result; if it's considered false, it prints "Even". In the second case, n%2 equals 1. It's odd. Sorting a List of TuplesWe will understand how to sort a list of Tuples with the help of an example shown below. Example: Output: [(5, 1), (3, 5), (2, 6), (4, 7)] Explanation: The above code sorts a list of tuples based on the second element of each tuple using the sorted() function with a custom comparison function defined using lambda. However, this code is for Python 2.x because it uses the cmp parameter removed in Python 3.x. The output sorts the tuples in ascending order based on their second elements. Compare Two StringsWe will now see an example demonstrating the comparison of two strings using the cmp() method. Example: Output: -1 1 0 Explanation: In the above program, in the first case, Hello comes before Python based on alphabetical order; therefore, the output will be -1. Similarly, in the second case, the output will be 1, and in the third case, you will get an output of 0 by comparing the strings based on alphabetical order. Comparing ListsIn the following section, we will look at some examples demonstrating the method of comparing lists in Python. Example: Output: -1 1 0 Explanation: The above code compares two lists element-wise using the cmp() method. The first print statement compares list1 with list2. It will print the -1. Similarly, the second print statement compares list2 with list1 and will print 1. The third print statement compares list1 with itself and prints 0 because they are equal. Custom Object ComparisonSuppose we have a custom class person with two attributes: name and age. Now, we will use cmp() to sort a Person object list based on age. Example: Output: John (20 years old) Doe (22 years old) Mac (25 years old) Explanation: The above code created a Person class with name and age attributes. Then, it sorts a list of Person objects based on their ages using the sorting_ppl function and will print their names and ages. cmp() function in Sorting AlgorithmsTo get the order of objects in a sorting method, the cmp() function is frequently utilized. Let us take an example: Example: Output: ["kiwi", "pear", "peach", "papaya"] Explanation: In the above program, the fruits are sorted in ascending order based on the length of their names. If two fruits are of the same length, their order remains unchanged. ConclusionThe cmp() function, once present in Python 2, facilitated value comparisons. However, it was deprecated in Python 3. Instead, Python 3 encourages comparison operators (==, !=, <, >, etc.) for more versatile comparisons. Migrating code from Python 2 to 3 necessitates replacing cmp() with modern alternatives. Next TopicPython beautifulsoup find all class |
This often makes projects that are to be delivered on a deadline heavily rely on core activities such as code review, automation tests, unit tests, and more. Unfortunately, there will be very little time for extensive documentation. Yet, regardless of how clean and neat the code...
10 min read
Introduction: Python, with its elegant syntax and powerful data structures, provides developers with various tools to manipulate and manage data efficiently. When working with dictionaries, a fundamental data structure in Python, developers often encounter two methods for accessing key-value pairs: dict.items() and dict.iteritems(). While both methods...
4 min read
? Threading is a technique for speeding up your code by doing numerous tasks at the same time. This may be accomplished in Python in two distinct manners: through the use of the multiprocessing module or the multithreading module. Multithreading is very beneficial for operations that need a...
17 min read
Introduction NLP has helped tremendously change the interaction of machines with human language. NLP techniques form the core of many applications we use every day, be it in the automatic translation of text or the determination of public opinion in social media or any other platform....
11 min read
Introduction: In this tutorial, we are learning to iterate over a set in Python. In Python, the Set is a collection of data types that are unordered, iterable, mutable, and have no equivalent elements. It is the unordered collection of unequal objects. This can be done...
11 min read
Introduction Apache Spark has proved itself to be an ideal and useful big data processing framework. PySpark, the Python API for Apache Sparks, provides a seamless ability to utilize this processing tool by the developers. The data frame API available in Pyspark is likened to pandas...
10 min read
? Debugging is a primary development activity that involves the localization, analysis, and possible bug removal from any malfunctioning part of a program. The core of debugging is to make the program do what it is supposed to do, producing proper, accurate, and reliable outputs. In this...
10 min read
Decision trees are a versatile and widely used machine learning algorithm. They are used for both classification and regression tasks, making them valuable tools for data analysis and predictive modeling. In this article, we will delve into the world of decision trees, exploring what they...
6 min read
? Introduction In statistics or machine learning, Mean Absolute Error (MAE) is used to check the model's accuracy in its prediction. It provides a way that it will check the predicted values against the actual ones in an easy manner. This article discusses the notion of Mean...
3 min read
is a powerful method used in laptop technological know-how and arithmetic to solve complex troubles by using breaking them down into smaller subproblems. Unlike brute-force tactics, which time and again remedy the same subproblems, DP optimizes computations by way of storing effects and reusing them....
8 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India