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.
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.
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.
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
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