2

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?

0

3 Answers 3

7
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
Sign up to request clarification or add additional context in comments.

Comments

5

simply use

a == b

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

Comments

-2

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

4 Comments

I presumed that == 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-false
Why would you reimplement a == b? And your examples for numbers is wrong, as @slothrop points out.
"There should be one-- and preferably only one --obvious way to do it. ". And "==" is the obvious way to do it. Don't confuse people.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.