Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unittest - compare list irrespective of order

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.

like image 333
Tom J Muthirenthi Avatar asked Apr 29 '18 22:04

Tom J Muthirenthi


People also ask

How do you assert two lists in Python?

Using list.sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.

How do you check if two orders are equal in Python?

A straightforward way to check the equality of the two lists in Python is by using the equality == operator. When the equality == is used on the list type in Python, it returns True if the lists are equal and False if they are not.


1 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

like image 165
AndrewHK Avatar answered Oct 22 '22 00:10

AndrewHK