[Solved] Compare two lists value-wise in Python [closed]


Suppose we have 2 list

x = ['3', '1']
y = ['1', '3']

Solution-1:

You can simply check whether the multisets with the elements of x and y are equal:

import collections

collections.Counter(x) == collections.Counter(y)

This requires the elements to be hashable; runtime will be in O(n), where n is the size of the lists.

Solution-2:

If the elements are also unique, you can also convert to sets (same asymptotic runtime, may be a little bit faster in practice):

set(x) == set(y)

Solution-3:

If the elements are neither hashable nor sortable you can use the following helper function. Note that it will be quite slow (O(n²)) and should generally not be used outside of the esoteric case of unhashable and unsortable elements.

def equal_ignore_order(a, b):
    """ Use only when elements are neither hashable nor sortable! """
    unmatched = list(b)
    for element in a:
        try:
            unmatched.remove(element)
        except ValueError:
            return False
    return not unmatched

solved Compare two lists value-wise in Python [closed]