pythonsetset-comprehension

Why does my set comprehension throw a TypeError?


I tried to change my original code with this set comprehension

next_states = {next_states | self.transition_function[(state, 
    input_value)] for state in e_closure_states}

But this code throws

TypeError: unhashable type: 'set'

Original code (working as expected). Also, it should be mentioned that self.transition_function[(state, input_value)] is set and that's why I am using union. Thanks in advance

for state in e_closure_states:
    next_states = next_states | self.transition_function[(state, input_value)]

Solution

  • The error TypeError: unhashable type: 'set' occurs because you're trying to add a set as an element of another set. As the error message implies, sets can only contain hashable elements, and sets themselves are unhashable.

    I am not entirely sure that I understand what you’re trying to do, but tell me if this code produces the same thing as the for loop which you know is correct:

    next_states = set.union(next_states, *(self.transition_function[(state, input_value)] for state in e_closure_states))
    

    self.transition_function[(state, input_value)] is copied from your code. That’s inside of a generator, as indicated by the parentheses. The asterisk (*) unpacks the generator into the set.union() call. You can read more about that here.