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
6
  • 5
    .. won't a == b serve your purpose? Commented Apr 6, 2013 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. Commented Apr 6, 2013 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. Commented Apr 6, 2013 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. Commented Oct 2, 2017 at 16:22
  • @yzn-pku That's good because I've been generating them for years now. Commented Oct 3, 2017 at 8:24

2 Answers 2

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

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]]).
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.