Quantcast
Channel: JS Tricks » Python
Viewing all articles
Browse latest Browse all 25

Python cmp method: Python tutorial

$
0
0

In this lesson we will learn about Python cmp method which is used to compare two items. The comparing items can be Lists or Numbers.

Python cmp method

Python cmp method is used to compare two Lists elements or two Numbers.

Syntax

Here is the syntax for Python cmp method:

cmp( item1 , item2 )

  • item1 — This is the first List/Number to be compared.
  • item2 — This is the second List/Number to be compared.

For Numbers:

If item1 < item2 then -1 is returned, if item1 == item2 then 0 is returned and if item1 > item2 then 1 is returned.

For List items:

The longer list will be larger. If both lists have the same data then cmp method will return 0.

Example with Lists

Here are some examples for Python cmp method with List items:

myList1 = [123, 743, 'abc']
myList2 = [628, 'abc', 455]
myList3 = [123, 743, 'abc']
myList4 = [966, 743, 877]

print cmp(myList1 , myList2)
print cmp(myList2 , myList3 )
print cmp(myList1 , myList3 )
print cmp(myList3 , myList4)

When we run above codes, it will produce the following output:

-1
1
0
-1

Example with Numbers

Here are some examples for Python cmp method with Numbers:

print cmp(15, 40)
print cmp(-20, 50)
print cmp(-15, -25)
print cmp(30, -32)
print cmp(101, 250)
print cmp(10, 10)

When you run the above codes, the output will look like this:

-1
-1
1
1
-1
0

The post Python cmp method: Python tutorial appeared first on JS Tricks.


Viewing all articles
Browse latest Browse all 25

Trending Articles