Bappy
Bappy

Reputation: 641

How can I compare the values of two lists in python?

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?

Upvotes: 2

Views: 9902

Answers (3)

sezina
sezina

Reputation: 492

simply use

a == b

the operator == will compare the value of a and b, no matter whether they refer to the same object.

Upvotes: 5

inspectorG4dget
inspectorG4dget

Reputation: 113955

@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 ;]

Upvotes: -2

jamylak
jamylak

Reputation: 133554

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

Upvotes: 7

Related Questions