best way to compare contents of 2 lists?

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Apr 24 02:12:38 EDT 2009


Esmail:
> oh, I forgot to mention that each list may contain duplicates.

Comparing the sorted lists is a possible O(n ln n) solution:

a.sort()
b.sort()
a == b

Another solution is to use frequency dicts, O(n):

from itertools import defaultdict
d1 = defaultdict(int)
for el in a:
    d1[el] += 1
d2 = defaultdict(int)
for el in b:
    d2[el] += 1
d1 == d2

As the arrays (Python lists) become large the second solution may
become faster.

Bye,
bearophile



More information about the Python-list mailing list