best way to compare contents of 2 lists?

David Robinow drobinow at gmail.com
Fri Apr 24 03:41:17 CEST 2009


On Thu, Apr 23, 2009 at 9:31 PM, Esmail <ebonak 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.
>
> 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.
>
> Thanks,
> Esmail
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

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)



More information about the Python-list mailing list