Check if two lists are equal

I am trying to write tests for my Django application, and I need to check many times if 2 lists have the same objects (i.e. every object in is also in B and vice versa).

I read about approvedLists / Sequence / Equal, etc., but for seeing if the lists have the same objects but in a different order (A = [a,b,c], B = [b,c,a])

, after which it returns an error which I don't want it to be an error because that they both have the same objects.

Is there a way to test this without looping through the lists?

+3


source to share


2 answers


You can use assertCountEqual

in Python 3 or assertItemsEqual

Python 2.

From the Python 3 docs for assertCountEqual

:



Check that the sequence first contains the same elements as the second, regardless of their order. When they do not, an error message appears listing the differences between the sequences.

Duplicate items are not ignored when comparing the first and the second. It checks if each element has the same count in both sequences. Equivalent to: assertEqual(Counter(list(first)), Counter(list(second)))

but also works on sequences of non-spliced ​​objects.

+8


source


If you are left with the list () datatype, then the cleanest way, if your lists are not too large, would be:

sorted(list_1) == sorted(list_2)

      



Look at this question (which is the same): Check if two unordered lists are equal

+2


source







All Articles