Chris
Chris

Reputation: 31270

Set function error in Python3: list is unhashable type

When run the following code in a scratch file, everything works:

x = [1,1,1]
print(set(x))
> {1}

And yet when I run the following code

class MyClass(object):
   def __init__(self):
         self.mylist = []
   def train(self,vector):
         self.mylist.append(vector)
         self.mylist = list(set(self.mylist))

I get the error, TypeError: unhashable type: 'list'.

What's the problem here?

Upvotes: 2

Views: 2552

Answers (2)

timgeb
timgeb

Reputation: 78780

When you issue

x = [1,1,1]
set(x)

you are building a set from the elements in x, which is fine because the elements of x are of type int and therefore immutable. However, mylist is a list of lists (because your vector objects are lists). The problem here is that the lists inside mylist are mutable and therefore cannot be hashed. That's why python refuses to build the set.

You can solve this issue by casting your vector lists to tuple. tuples are immutable and therefore Python has no problem with building a set from a list of tuple objects.

Demo:

>>> lst = [[1,2], [3,4]]
>>> set(lst)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> set(map(tuple, lst))
set([(1, 2), (3, 4)])

Upvotes: 4

Marcin
Marcin

Reputation: 49886

This is correct. List is unhashable because it's mutable. Use a tuple instead.

Upvotes: 3

Related Questions