best way to compare contents of 2 lists?
tjreedy at udel.edu
Fri Apr 24 17:53:07 CEST 2009
Steven D'Aprano wrote:
> On Thu, 23 Apr 2009 21:51:42 -0400, Esmail wrote:
>>> set(a) == set(b) # test if a and b have the same elements
>>> # check that each list has the same number of each element # i.e.
>>> [1,2,1,2] == [1,1,2,2], but [1,2,2,2] != [1,1,1,2] for elem in set(a):
>>> a.count(elem) == b.count(elem)
>> Ah .. this part would take care of different number of duplicates in the
>> lists. Cool.
> At significant cost of extra work.
> Counting the number of times a single element occurs in the list is O(N).
> Counting the number of times every element occurs in the list is O(N**2).
A frequency dict should be O(n) also, and hence faster than sorting.
> Sorting is O(N*log N), so for large lists, sorting will probably be much
More information about the Python-list