Search code examples
pythonlistunit-testingcomparison

Unittest that every element matches in 2 lists


Unit testing that 2 lists are the same in Python. Seems like it fails if they're not in order. Thought about sorting them first or converting to a set. But the set method isn't true, if there's duplicate etc

l1 = ['c-00355', 'b-0ae53', 'c-07d32']
l2 = ['b-0ae53', 'c-07d32' ,'c-00355']

l1 == l2
False

set(l1) == set(l2)
True

sorted(l1) == sorted(l2)
True


Solution

  • Maybe consider a collections.Counter - it's a kind of cross between a set and a list sort and then comparing it... it's __eq__ method checks each key is present in both and that the quantities match, eg:

    from collections import Counter                                                   
    
    l1 = ['c-00355', 'b-0ae53', 'c-07d32']                                            
    l2 = ['b-0ae53', 'c-07d32' ,'c-00355']                                            
    
    Counter(l1) == Counter(l2)                                                        
    # True
    
    l2 = ['b-0ae53', 'c-07d32' ,'c-00355', 'c']                                       
    
    Counter(l1) == Counter(l2)                                                        
    # False