2

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?

7
  • What type is vector? Commented Dec 15, 2015 at 20:04
  • 1
    You can only hash values that are immutable/unchanging (otherwise really weird things could happen). If vector is a list, it can't go inside a set. You'd probably want to use a tuple (immutable list) instead. Commented Dec 15, 2015 at 20:05
  • ah, that is it. it is a list. Is there a way to do what I am doing? for instance, I could pair the list with an integer value, since I am in a bounded, integer state space... Commented Dec 15, 2015 at 20:06
  • Got it, cool--thanks guys. Commented Dec 15, 2015 at 20:07
  • If you could clarify what you expect train to do, a fix could either be to change vector to a tuple or to use .extend rather than .append Commented Dec 15, 2015 at 20:07

2 Answers 2

4

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)])
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.