I want to compare the values of two lists.
For example:
a = [1, 2, 3]
b = [1, 2, 3]
I need to check if a is same as b or not. How do I do that?
a == b
This is a very simple test, it checks if all the values are equal.
If you want to check if a and b both reference the same list, you can use is.
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b # a and b have the same values but refer to different lists in memory
False
>>> a = [1, 2, 3]
>>> b = a
>>> a is b # both refer to the same list
True
@jamylak's answer is what I would go with. But if you're looking for "several options", here's a bunch:
>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a == b
True
OR
def check(a,b):
if len(a) != len(b):
return False
for i in xrange(len(a)):
if a[i] != b[i]:
return False
return True
OR
>>> len(a)==len(b) and all((a[i]==b[i] for i in xrange(len(a))))
True
OR
def check(a,b):
if len(a) != len(b):
return False
for i,j in itertools.izip(a,b):
if i != j:
return False
return True
OR
>>> all((i==j for i,j in itertools.izip(a,b)))
True
OR (if the list is made up of just numbers)
>>> all((i is j for i,j in itertools.izip(a,b)))
True
OR
>>> all((i is j for i,j in itertools.izip(a,b)))
True
Hope that satiates your appetite ;]
== would already include the optimization len(a) != len(b), do you know how that equality check is implemented and where I could view the source?i is j works only for small numbers, and the meaning of "small" is implementation dependent. See: stackoverflow.com/questions/11476190/why-0-6-is-6-falsea == b? And your examples for numbers is wrong, as @slothrop points out.