assert list of list equality without order in python

  • Last Update :
  • Techknowledgy :

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()

Slightly faster version of the implementation (If you know that most couples lists will have different lengths):

def checkEqual(L1, L2):
   return len(L1) == len(L2) and sorted(L1) == sorted(L2)

Comparing:

>>> timeit(lambda: sorting([1, 2, 3], [3, 2, 1]))
2.42745304107666
   >>>
   timeit(lambda: lensorting([1, 2, 3], [3, 2, 1]))
2.5644469261169434 # speed down not much(
      for large lists the difference tends to 0)

   >>>
   timeit(lambda: sorting([1, 2, 3], [3, 2, 1, 0]))
2.4570400714874268
   >>>
   timeit(lambda: lensorting([1, 2, 3], [3, 2, 1, 0]))
0.9596951007843018 # speed up

Given

l1 = [a, b]
l2 = [b, a]
assertCountEqual(l1, l2) # True

In Python >= 2.7, the above function was named:

assertItemsEqual(l1, l2) # True

Via six module (Any Python version)

import unittest
import six
class MyTest(unittest.TestCase):
   def test(self):
   six.assertCountEqual(self, self.l1, self.l2) # True

Converting your lists to sets will tell you that they contain the same elements. But this method cannot confirm that they contain the same number of all elements. For example, your method will fail in this case:

L1 = [1, 2, 2, 3]
L2 = [1, 2, 3, 3]

You are likely better off sorting the two lists and comparing them:

def checkEqual(L1, L2):
   if sorted(L1) == sorted(L2):
   print "the two lists are the same"
return True
else:
   print "the two lists are not the same"
return False

Suggestion : 2

map() function applies the given lambda function to each element of both the lists and stores the result to a new array. Which in our case will be a bool array because inside the lambda function we are checking if both the elements are equal or not. ,We can create sorted versions of both the lists. If original lists contain the same elements but in different order, then the order of elements must be similar in sorted versions of the lists. So, by comparing sorting versions of lists we can find out if lists are equal or not. For example, ,Suppose we have two lists and we want to check if both the lists are equal or not. There can be two meanings of 2 equality here,,In this article we will discuss 8 different ways to check if two lists are equal or not.

Suppose we have two lists,

first_list = [10, 10, 11, 12, 12, 13, 14, 16, 15, 16, 12]
sec_list = [16, 12, 13, 14, 15, 16, 10, 11, 12, 10, 12]

We can create sorted versions of both the lists. If original lists contain the same elements but in different order, then the order of elements must be similar in sorted versions of the lists. So, by comparing sorting versions of lists we can find out if lists are equal or not. For example,

def check_if_equal(list_1, list_2):
   ""
" Check if both the lists are of same length and if yes then compare
sorted versions of both the list to check
if both of them are equal
i.e.contain similar elements with same frequency.
""
"
if len(list_1) != len(list_2):
   return False
return sorted(list_1) == sorted(list_2)

first_list = [10, 10, 11, 12, 12, 13, 14, 16, 15, 16, 12]
sec_list = [16, 12, 13, 14, 15, 16, 10, 11, 12, 10, 12]

if check_if_equal(first_list, sec_list):
   print('Lists are equal i.e. contain similar elements with same frequency')
else:
   print('Lists are not equal')

For example,

import collections

def check_if_equal_2(list_1, list_2):
   ""
" Check if both the lists are of same length and then get the frequency of each element in list using collections.Counter.Then Compare
if both the Counter
objects are equal or not to confirm
if lists contain similar elements with same frequency ""
"
if len(list_1) != len(list_2):
   return False
return collections.Counter(list_1) == collections.Counter(list_2)

first_list = [10, 10, 11, 12, 12, 13, 14, 16, 15, 16, 12]
sec_list = [16, 12, 13, 14, 15, 16, 10, 11, 12, 10, 12]

if check_if_equal_2(first_list, sec_list):
   print('Lists are equal i.e. contain similar elements with same frequency')
else:
   print('Lists are not equal')

We can create two sorted numpy arrays from our lists and then we can compare them using numpy.array_equal() to check if both contains same elements. For example,

import numpy as np

first_list = [10, 10, 11, 12, 12, 13, 14, 16, 15, 16, 12]
sec_list = [16, 12, 13, 14, 15, 16, 10, 11, 12, 10, 12]

# Convert both lists to sorted numpy arrays, then compare
# them to check
if both are equal or not
result = np.array_equal(np.array(first_list).sort(), np.array(sec_list).sort())

if result:
   print('Lists are equal i.e. contain similar elements with same frequency')
else:
   print('Lists are not equal')

Suggestion : 3

Last Updated : 24 Nov, 2018

Output :

The first list is: [1, 2, 4, 3, 5]
The second list is: [1, 2, 4, 3, 5]
The lists are identical

Suggestion : 4

An extensive list of Python testing tools including functional testing frameworks and mock object libraries.,Note that in order to test something, we use one of the assert*() methods provided by the TestCase base class. If the test fails, an exception will be raised with an explanatory message, and unittest will identify the test case as a failure. Any other exceptions will be treated as errors.,Changed in version 3.1: In 3.1 this was changed to add the test name to the short description even in the presence of a docstring. This caused compatibility issues with unittest extensions and adding the test name was moved to the TextTestResult in Python 3.2.,Return an instance of the test result class that should be used for this test case class (if no other result instance is provided to the run() method).

import unittest

class TestStringMethods(unittest.TestCase):

   def test_upper(self):
   self.assertEqual('foo'.upper(), 'FOO')

def test_isupper(self):
   self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())

def test_split(self):
   s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
   s.split(2)

if __name__ == '__main__':
   unittest.main()
...
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Ran 3 tests in 0.000 s

OK
test_isupper(__main__.TestStringMethods)...ok
test_split(__main__.TestStringMethods)...ok
test_upper(__main__.TestStringMethods)...ok

   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Ran 3 tests in 0.001 s

OK
python - m unittest test_module1 test_module2
python - m unittest test_module.TestClass
python - m unittest test_module.TestClass.test_method
python - m unittest tests / test_something.py
python - m unittest - v test_module