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?

jamylak
  • 128,818
  • 30
  • 231
  • 230
Bappy
  • 621
  • 1
  • 7
  • 16

3 Answers3

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
jamylak
  • 128,818
  • 30
  • 231
  • 230
5

simply use

a == b

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

sezina
  • 482
  • 2
  • 5
  • 18
-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 ;]

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • 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? – jamylak Jul 14 '12 at 08:17
  • 1
    `i is j` works only for small numbers, and the meaning of "small" is implementation dependent. See: http://stackoverflow.com/questions/11476190/why-0-6-is-6-false – slothrop Jul 14 '12 at 09:30
  • 1
    Why would you reimplement `a == b`? And your examples for numbers is wrong, as @slothrop points out. – Ned Batchelder Jul 14 '12 at 11:31
  • ["There should be one-- and preferably only one --obvious way to do it. "](https://www.python.org/dev/peps/pep-0020/#id3). And "==" is *the* obvious way to do it. Don't confuse people. – Mayou36 Dec 11 '17 at 10:05