Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if two lists are equal [duplicate]

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

I read on the assertLists/Sequence/Equal etc but for what I saw if the lists have the same objects but in a different order (A = [a,b,c], B = [b,c,a]) then it returns an error, which I don't want it to be an error because they both have the same objects.

Is there a way to check this without looping the lists?

like image 772
brad Avatar asked May 21 '15 08:05

brad


2 Answers

You can use assertCountEqual in Python 3, or assertItemsEqual in Python 2.

From the Python 3 docs for assertCountEqual:

Test that sequence first contains the same elements as second, regardless of their order. When they don’t, an error message listing the differences between the sequences will be generated.

Duplicate elements are not ignored when comparing first and second. It verifies whether each element has the same count in both sequences. Equivalent to: assertEqual(Counter(list(first)), Counter(list(second))) but works with sequences of unhashable objects as well.

like image 121
Alasdair Avatar answered Oct 13 '22 20:10

Alasdair


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

sorted(list_1) == sorted(list_2)

Have a look at this Question (which is the same): Check if two unordered lists are equal

like image 6
Tanguy Serrat Avatar answered Oct 13 '22 21:10

Tanguy Serrat