The best way to check if two lists have identical values

Peter Otten __peter__ at web.de
Thu Feb 25 08:46:56 EST 2010


mk wrote:

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

I don't think the above is a relevant part of the problem.

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

No you haven't. [1, 1, 0] and [1, 0, 0] are considered equal by your 
algorithm.

> I was wondering if there's a better / shorter / faster way to do this --
> not necessarily in the same variant, e.g. variant where order of two
> lists matters would be interesting as well.

sorted(left_list) == sorted(right_list)

should be good enough in most cases where you do care for repetitions but 
not order.

Peter



More information about the Python-list mailing list