5

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?

geckon
  • 8,316
  • 4
  • 35
  • 59
brad
  • 491
  • 1
  • 9
  • 24
  • If the objects have a unique combination of attributes, you can sort them and use the functions you metioned. – Peter Clause May 21 '15 at 08:31
  • Do you care about duplicates? If not you could turn your lists into sets and compare them. set(A) == set(B). – Stephen Paulger May 21 '15 at 08:45
  • I have published a gist of my old code, where i was testing different methods of comparing two lists: https://gist.github.com/sobolevn/928cb960b1ce228a586d – sobolevn May 21 '15 at 10:59

2 Answers2

11

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.

Community
  • 1
  • 1
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Useful answer but I am surprised this is from the Unit Test Framework. Isn't there some regular function in Python 2.7 which can handle this? – Elmex80s Mar 08 '17 at 10:40
7

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

Community
  • 1
  • 1
Tanguy Serrat
  • 322
  • 1
  • 7