best way to compare contents of 2 lists?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Apr 24 04:25:23 EDT 2009


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). 
Sorting is O(N*log N), so for large lists, sorting will probably be much 
cheaper.


-- 
Steven



More information about the Python-list mailing list