1

Hello I want to compare a list to another list in Python where the sequence of the elements doens't matters

eg

list=[1,2,3]

should be equal to list2=[3,2,1] and equal to list3=[3,1,2] etc. I want to do it dynamically because I don't know how many elements exist at the list? Is there any quick way to do it? The only way I came up with is to search each list for the elements of the other list but this has O(n^2). Also I cannot sort the list since in my implementation the list are list of list. I just want an answer for the simple version of the problem and then modify it! Can you help me?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
JmRag
  • 1,443
  • 7
  • 19
  • 56

2 Answers2

4

You can simply convert the lists to sets and then simply check if they are equal

list1, list2, list3 = [1, 2, 3], [2, 3, 1], [1, 2, 3, 4]
print set(list1) == set(list2)    # True
print set(list2) == set(list3)    # False
print set(list1) == set(list3)    # False

If you want to make sure that the the elements exists only the same number of times as in the other list, you can use collections.counter (Thanks @delnan), like this

list1, list2, list3, list4 = [1, 2, 3], [2, 3, 1], [1, 2, 3, 4], [1, 2, 3, 3]
from collections import Counter
print Counter(list1) == Counter(list2)    # True
print Counter(list2) == Counter(list3)    # False
print Counter(list1) == Counter(list3)    # False
print Counter(list1) == Counter(list4)    # False
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 1
    @NG. Perhaps it does exactly what OP wants, hard to tell. And if not, `collections.Counter` works just as well. –  Jan 26 '14 at 14:57
  • @NG. I dont have any duplicates so it will work! Thx for the answer I will mark it as soon as possible! – JmRag Jan 26 '14 at 14:59
  • @delnan Thanks :) I have included that in the answer :) – thefourtheye Jan 26 '14 at 15:00
2

If the lists are allowed to have the duplicate elements:

def list_eql(x, y):
    return sorted(x) == sorted(y)

If the lists don't have the duplicate elements:

def list_eql(x, y):
    return set(x) == set(y)

EDIT: as I've understood your question x and y are the lists of lists. In that case set solution won't work (since lists are mutable) and you'll need to convert the inner lists to tuples first:

def list_eql(x, y):
    return set(map(tuple, x)) == set(map(tuple, y))
Nigel Tufnel
  • 11,146
  • 4
  • 35
  • 31
  • 2
    Just checking the length of two lists won't work if lists have duplicates. Consider lists x=[1,1,2,2,3], y=[1,1,1,2,3]. Your function will return true, even if these two lists are not equal. – santosh-patil Jan 26 '14 at 15:10