'"TypeError: unhashable type: 'list'" when using .add to add array to list. Any work around ? (Python)

I'm trying to implement a breadth first search and am getting "TypeError: unhashable type: 'list'" on the visited.add(state) command. The initState input is an array of numbers ([2,2,0,0,1]) and the return value of future_State() is a list of arrays in the same format. Any thoughts on how to solve this?

Some research pointed to a hash() method but I couldnt get it to work :/

      def BFS(initState):
            initState = currentState
            if isGoal(initState) :
                return initState

            visited = set()
            queue = [initState]

            while queue:
                state = queue.pop()
                if isGoal(state) == True:
                    return state

                visited.add(state)

                for child in future_State(state):
                    if child in visited:
                        continue
                    if child not in queue:
                        queue.append(child)


Solution 1:[1]

The sets in Python are implemented with an hash table. The error message you get means that you can't add a list to a set, because the hash key can't be computed for that type of variable (the list). If you want to add the values of state into the visited array, you can perform a union:

visited = visited.union(state)

Otherwise, if you want that each element of the set is a list, you should use a list for visited instead of a set and implement a solution to avoid duplicates.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1