Search code examples
pythonlistmatrixuniqueelement

how to check all items in a list/matrix are different in python


given an NxN matrix of lists how can i determine that all the elements in the list are unique example inputs:

(check_unique_elem([[8, 3, 4], [1, 5, 9], [6, 7, 2]]))
example output:
 True
(check_unique_elem([[1]]))
True
(check_unique_elem([[2,3],[6,5],[6,7]]))
False

Solution

  • If the elements are all hashable (the ints in your example are), you can add them to a set checking for duplicates.

    def check_unique_elem(L):
        seen = set()
        for row in L:
            for i in row:
                if i in seen:
                    return False
                seen.add(i)
        return True
    

    This has the advantage of exiting as soon as the first duplicate is found (shortcircuiting)