unittest – compare list irrespective of order

Question:

I am doing a unit test on two list of list values:

self.assertEqual(sale, [['1',14], ['2',5], ['3',7], ['4',1]])

But it gives the below error:

AssertionError: Lists differ: [['1', 14], ['4', 1], ['2', 5], ['3', 7]] != [['1'
, 14], ['2', 5], ['3', 7], ['4', 1]]

First differing element 1:
['4', 1]
['2', 5]

- [['1', 14], ['4', 1], ['2', 5], ['3', 7]]
+ [['1', 14], ['2', 5], ['3', 7], ['4', 1]]

How can I make this scenario pass, Prevent the assertEqual function to avoid checking the order of the elements in the list.

Asked By: Tom J Muthirenthi

||

Answers:

Since Python lists keep track of order, you’ll need some way to make sure the items are in the same order.

A set might work, if all items are unique. If they aren’t unique you’ll lose information on the duplicates.

Sorting the lists before you compare them will probably be your best bet. It will keep all the data intact, and put them in the same order in each list.

Here is a link to the different built in sorting methods for lists in Python 3.
https://docs.python.org/3/howto/sorting.html

Answered By: AndrewHK

You want assertCountEqual.

For assertCountEqual(a, b), it passes if:

a and b have the same elements in the same number, regardless of their order.

Answered By: Tim Tisdall
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.