pythonlistsetset-union

Compare elements in two lists in python


I have two lists as below:

a = ['abc','def', 'ghi'], b=['ZYX','WVU']

and want to confirm whether union of both lists is equal to superset

c = ['ZYX', 'def', 'WVU', 'ghi', 'abc'] 

I have tried following:

>>> print (c == list(set(b).union(c)))
>>> False

Can anybody show what I am missing here?


Solution

  • Just use set method because the items order in the lists are different and that's why you've received False as result.

    print (set(c) == set(list(set(b).union(c))))
    

    Another solution is to use Counter class. The Counter approach should be more efficient for big lists since it has linear time complexity (i.e. O(n))

    from collections import Counter
    Counter(c) == Counter(list(set(b).union(c))))