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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With