best way to compare contents of 2 lists?

MRAB google at mrabarnett.plus.com
Thu Apr 23 21:52:44 EDT 2009


Esmail wrote:
> Esmail wrote:
>> What is the best way to compare the *contents* of two different
>> lists regardless of their respective order? The lists will have
>> the same number of items, and be of the same type.
>>
>> E.g. a trivial example (my lists will be larger),
>>
>> a=[1, 2, 3]
>>
>> b=[2, 3, 1]
>>
>> should yield true if a==b
>>
>> I suppose I could sort them and then compare them. I.e.,
>>
>> sorted(a)==sorted(b)
>>
>>
>> I am wondering if there is a more efficient/preferred way to do so.
> 
> oh, I forgot to mention that each list may contain duplicates. So I
> suppose this means I would have to sort the two lists and compare them
> afterall, unless there's another way?
> 
You could use Raymond Hettinger's Counter class:

http://code.activestate.com/recipes/576611/

on both lists and compare them for equality.



More information about the Python-list mailing list