The best way to check if two lists have identical values

Arnaud Delobelle arnodel at googlemail.com
Thu Feb 25 08:55:26 EST 2010



mk wrote:
> Hello everyone,
>
> I have stumbled upon this seemingly trivial problem: the answer is not
> there in http://www.python.org/doc/faq/programming/, and googling does
> not return many references really (at least for me).
>
> I have come up with this:
>
> def qips_identical(q, oldq):
>      qips = map(operator.itemgetter(1), q)
>      oldqips = map(operator.itemgetter(1), oldq)
>      if len(qips) != len(oldqips):
>          return False
>      dif = set(qips) ^ set(oldqips)
>      if len(dif):
>          return False
>      return True
>
> There's a number of complications here, depending on definition of
> 'lists with identical values', like whether the same value can be
> repeated different number of times in two lists, or whether the order of
> values matters.
>
> In above example I assumed that the same values have to be repeated the
> same numbers of times in both lists and that order doesn't matter so
> long as the values are the same.

Your code checks if the two lists have the same length and the same
elements, but not necessarily the same number of each elements. E.g.

    qips = [1, 1, 2]
    oldqips = [1, 2, 2]

will return True

If you want to check if each value has the same number of occurences,
you can do

    return sorted(qips) == sorted(oldqips)

assuming that all elements in the lists are comparable.

--
Arnaud



More information about the Python-list mailing list