best way to compare contents of 2 lists?
gallium.arsenide at gmail.com
Fri Apr 24 04:09:10 CEST 2009
Esmail <ebo... at hotmail.com> 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.
"Best" can mean different things. Fastest? Shortest code? Most
> David Robinow 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.
It takes care of the duplicates, but so does your initial solution,
which I like best:
This is concise, clear, and in my opinion, the most Pythonic. It may
well even be the fastest. (If you didn't have to match up the numbers
of duplicates, the set solution would be most Pythonic and probably
More information about the Python-list