How to assert two list contain the same elements in Python?

satoru picture satoru · Oct 10, 2012 · Viewed 161.9k times · Source

When writing test cases, I often need to assert that two list contain the same elements without regard to their order.

I have been doing this by converting the lists to sets.

Is there any simpler way to do this?

EDIT:

As @MarkDickinson pointed out, I can just use TestCase.assertItemsEqual.

Notes that TestCase.assertItemsEqual is new in Python2.7. If you are using an older version of Python, you can use unittest2 - a backport of new features of Python 2.7.

Answer

flazzarini picture flazzarini · Aug 5, 2015

As of Python 3.2 unittest.TestCase.assertItemsEqual(doc) has been replaced by unittest.TestCase.assertCountEqual(doc) which does exactly what you are looking for, as you can read from the python standard library documentation. The method is somewhat misleadingly named but it does exactly what you are looking for.

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

Here a simple example which compares two lists having the same elements but in a different order.

  • using assertCountEqual the test will succeed
  • using assertListEqual the test will fail due to the order difference of the two lists

Here a little example script.

import unittest


class TestListElements(unittest.TestCase):
    def setUp(self):
        self.expected = ['foo', 'bar', 'baz']
        self.result = ['baz', 'foo', 'bar']

    def test_count_eq(self):
        """Will succeed"""
        self.assertCountEqual(self.result, self.expected)

    def test_list_eq(self):
        """Will fail"""
        self.assertListEqual(self.result, self.expected)

if __name__ == "__main__":
    unittest.main()

Side Note : Please make sure that the elements in the lists you are comparing are sortable.