9

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.

2
  • 2
    You could sort them, you could compare their lengths and compare them as sets, etc. Apr 29, 2018 at 22:14
  • @chrisz. Option 2 is no good: 1, 1, 2 vs 1, 2, 2 Apr 29, 2018 at 22:17

2 Answers 2

6

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

2
  • Hmm, I think I answered the first part of your question; "how can I make this scenario pass" but not the second "prevent the assertEqual function to avoid checking the order of the elements in the list."
    – AndrewHK
    Apr 29, 2018 at 22:17
  • I think your answer is perfectly fine. I don't know why you got a downvote. The second part makes no actual sense. If you don't want to modify the originals, just use sorted instead of in-place sort. Apr 29, 2018 at 22:33
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.