-3

Possible Duplicate:
Determine if 2 lists have the same elements, regardless of order?
Match two lists of letters in Python

I have list a and list b. So I need to find, if lists have equal elements. I have no idea, but I am thinking about using collections.

Community
  • 1
  • 1
JohnDow
  • 1,242
  • 4
  • 22
  • 40

2 Answers2

4

Assuming you don't care about order. There are a few options here, the best solution depends on the contents of your lists. Here are a few possibilities in order of preference (and restrictions):

  • If there are no duplicates, and all items are hashable:

    set(a) == set(b)
    
  • If there are duplicates, and all items are of the same type:

    sorted(a) == sorted(b)
    
  • If there are duplicates and the list may have mixed types, and all types are hashable:

    collections.Counter(a) == collections.Counter(b)
    
  • If there are duplicates, the list may have mixed types, and some elements may not be hashable (there must be a better way to do this, but what I came up with was to turn each element into a tuple with the string representation of the type, followed by the value):

    keyfunc = lambda x: (str(type(x)), x)
    sorted(a, key=keyfunc) == sorted(b, key=keyfunc)
    
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • "wrapping each element in a tuple allows ordering between different types" - are you sure? Doesn't work for me (3.2) – georg Nov 05 '12 at 22:50
  • @thg435 Oops, I originally had `lambda x: (type(x), x)` and must have tested just wrapping the value on 2.x thinking it was 3.2 (I have a parallel installation). It turns out that doesn't even work though, current solution is `lambda x: (str(type(x)), x)`, but there must be a better way. – Andrew Clark Nov 05 '12 at 22:53
  • How about `key=repr` (just kidding)) Otherwise, a good answer to a remarkably poor question. – georg Nov 05 '12 at 23:07
0
>>> all(x in b for x in a)
yurisich
  • 6,991
  • 7
  • 42
  • 63
  • This won't work if `a` is a smaller list. For example this will return true when `a = [0, 1]` and `b = [0, 1, 2, 3, 4, 5]` but it should return false. It checks if `a` is contained within `b`, not if they are equal. – Tim Nov 05 '12 at 22:49