0

I have two lists. the contents may be different. I best method to check and return True if both list have same contents. For eg: [3,4,5] and [4,3,5] then must Return True

Here is what i tried.

>>> x=[3,4,5]
>>> y=[4,3,5]
>>> x==y
False
>>> x is y
False
>>> x in y
False

it doesn't worked, but when i tried these with sort() it worked :

>>> x.sort()
>>> y.sort()
>>> x==y
True

is this is correct method? Any thing better than this??

suhailvs
  • 20,182
  • 14
  • 100
  • 98

2 Answers2

3

You already have one of the better methods to determine if the content in both lists is identical.

If your condition is that the content must be the same, but the order is optional, then using sort() and comparing them is a perfectly good solution.

Or you could do a method that does not involve sorting both lists and then also comparing them. This assumes the lists contain ints. But something similar could be done for other data types.

Using Counter you do not need to sort them, and you can make sure they have the same number of each element.

>>> from collections import Counter
>>> a = [1,2,3,4]
>>> b = [4,3,2,1]
>>> Counter(a) == Counter(b)
True
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
  • 1
    This seems indeed the best method and is `O(n)`, if the items are hashable. Next best is sorting for items that can be ordered bot not hashed, which is `O(n log(n))`. A final method is `O(n^2)` if items are not hashable and cannot be ordered. See the [winning answer](http://stackoverflow.com/a/7829388/2647279) of the duplicate reported above. – Bas Swinckels Oct 08 '13 at 08:48
0

You can use use set here: set(x) == set(y)

Mandar Pande
  • 12,250
  • 16
  • 45
  • 72