best way to compare contents of 2 lists?

John Yeung gallium.arsenide at gmail.com
Thu Apr 23 22:09:10 EDT 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
readable?

> 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:

> sorted(a)==sorted(b)

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
fastest.)

John



More information about the Python-list mailing list