10

Given two lists:

a = [[1,2],[3,4]]
b = [[1,2],[3,4]]

How would I write compare such that:

compare(a,b) => true
sdasdadas
  • 23,917
  • 20
  • 63
  • 148
  • 5
    .. won't `a == b` serve your purpose? – DSM Apr 06 '13 at 20:41
  • 2
    Not necessarily. For example, if the elements of the list were strings (and you wanted case insensitivity), or floats and you wanted a tolerance for numerical error, then `==` wouldn't work. Depends on your expected types. – DSM Apr 06 '13 at 20:44
  • @sdasdadas Try out a few things before asking questions :) The lists are Python objects; `==` tests equality for Python objects. It's the same if testing the equality of two normal lists. – Rushy Panchal Apr 06 '13 at 20:45
  • ... Maybe I'm the minority but I'm glad that there's always an exact dumb question on SO when I encounter a dumb question myself. – yzn-pku Oct 02 '17 at 16:22
  • @yzn-pku That's good because I've been generating them for years now. – sdasdadas Oct 03 '17 at 08:24
  • Related [`numpy`]: [Comparing two numpy arrays for equality, element-wise](https://stackoverflow.com/questions/10580676/comparing-two-numpy-arrays-for-equality-element-wise) – jpp Mar 17 '18 at 16:39

2 Answers2

14

Do you want this:

>>> a = [[1,2],[3,4]]
>>> b = [[1,2],[3,4]]
>>> a == b
True

Note: == not useful when List are unordered e.g (notice order in a, and in b)

>>> a = [[3,4],[1,2]]
>>> b = [[1,2],[3,4]]
>>> a == b
False

See this question for further reference: How to compare a list of lists/sets in python?

Edit: Thanks to @dr jimbob

If you want to compare after sorting you can use sorted(a)==sorted(b).
But again a point, if c = [[4,3], [2,1]] then sorted(c) == sorted(a) == False because, sorted(c) being different [[2,1],[4,3]] (not in-depth sort)

for this you have to use techniques from linked answer. Since I am learning Python too :)

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • 1
    The last part isn't right. `a.sort()` sorts `a` in place and then returns `None`. So `a.sort() == None` will be `True`, and your `a.sort()==b.sort()` evaluates to `None == None`. Try getting a `False`; e.g., let `b=[]`. (Note its better style to use `is` comparison when checking for None). Now, `sorted(a) == sorted(b)` will work. Granted note if you have `a = [[1,2],[3,4]]`, `b = [[3,4],[1,2]]` and `c = [[4,3], [2,1]]`, then only `sorted(a)` and `sorted(b)` will be equal (both being `[[1,2],[3,4]]`), with `sorted(c)` being different (`[[2,1],[4,3]]`). – dr jimbob Apr 07 '13 at 00:15
3

Simple:

def compare(a, b): return a == b

Another way is using lambda to create an anonymous function:

compare = lambda a, b: a == b
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94