Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparison of list using cmp or ==

Tags:

python

I have two list which each contain read from a file.

Should I use cmp(list1,list2) or (list1 == list2)?

#! /usr/bin/env py

data = None
with open("sample",'r+') as f:
    data = f.readlines()
data[-1] = "abhishe"
data_1 = None
with open("cp.log",'r+') as f:
    data_1 = f.readlines()
data_1[-1] = "Goswami"

print "\n\n\n"
print data == data_1
print cmp(data,data_1)
like image 488
user765443 Avatar asked Sep 07 '13 15:09

user765443


2 Answers

You will very rarely need to use cmp. cmp has the same effect as testing <, == and >, but it is less readable.

In your case, use == as it will perform deep list equality testing.

like image 146
nneonneo Avatar answered Nov 15 '22 12:11

nneonneo


If you are only interested in their equality, then I would say use the equality operator ==.

The cmp() function gives slightly different info, as the documentation describes:

cmp() - Compare the two objects x and y and return an integer according to the outcome. The return value is:

  • negative if x < y
  • zero if x == y
  • strictly positive if x > y.

In your case, the "expected" result would be zero, a falsy value, which is not to intuitive if you are actually testing for equality.

like image 30
Lix Avatar answered Nov 15 '22 13:11

Lix