Check if two unordered lists are equal [duplicate]
Python has a built-in datatype for an unordered collection of (hashable) things, called a
set. If you convert both lists to sets, the comparison will be unordered.
set(x) == set(y)
EDIT: @mdwhatcott points out that you want to check for duplicates.
set ignores these, so you need a similar data structure that also keeps track of the number of items in each list. This is called a multiset; the best approximation in the standard library is a
import collections compare = lambda x, y: collections.Counter(x) == collections.Counter(y) compare([1,2,3], [1,2,3,3])Falsecompare([1,2,3], [1,2,3])Truecompare([1,2,3,3], [1,2,2,3])False
If elements are always nearly sorted as in your example then builtin
.sort() (timsort) should be fast:
1,1,2] b = [1,2,2] a.sort() b.sort() a == bFalsea = [
If you don't want to sort inplace you could use
In practice it might always be faster then
collections.Counter() (despite asymptotically
O(n) time being better then
.sort()). Measure it; If it is important.