Set comprehension gives "unhashable type" (set of list) in Python

Hendrik picture Hendrik · Feb 21, 2017 · Viewed 7.4k times · Source

I have the following list of tuples:

list_of_tuples = [('True', 100, 'Text1'),
                  ('False', 101, 'Text2'),
                  ('True', 102, 'Text3')]

I want to collect all second elements of each tuple into a set:

my_set = set()
my_set.add({tup[1] for tup in list_of_tuples})

But it throws the following error:

TypeError: unhashable type: 'set'

When I print out the respective elements in the iteration, it shows that the result of the set comprehension contains not the expected scalars but lists:

print {tup[1] for tup in list_of_tuples}

set([100, 101, 102])

Why does this happen? Why does this put the elements into a list first and put then the list into a set without any hint to list? How could I correct my solution?

Answer

McGrady picture McGrady · Feb 21, 2017

The individual items that you put into a set can't be mutable, because if they changed, the effective hash would change and the ability to check for inclusion would break down.

The content of set can be changed over its lifetime.So this is illegal.

So just try to use this:

list_of_tuples = [('True', 100, 'Text1'),
                  ('False', 101, 'Text2'),
                  ('True', 102, 'Text3')]


my_set= { tup[1] for tup in list_of_tuples }
# set comprehensions with braces
print my_set

Hope this helps.