tags:

views:

75

answers:

7
 closed = set() -here closed is a set

node is (5,5)

The error occurse at execution time.

Error is:

list objects are unhashable

the program is:

closed.add(node)
for val in closed:
      print val   

Node is the output of stack.

node = stack.pop() - it gives me...(5,5)

Traceback:

File "/home/", line 99, in depthFirstSearch
    closed.add(node)
TypeError: list objects are unhashable
A: 

Assuming node is a list, and given that tuples are hashable.

closed.add(tuple(node))
DiggyF
A: 

No problem with that - are you sure it is this portion of code? Can you post the traceback?

>>> closed = set()
>>> node = (5,5)
>>> closed.add(node)
>>> closed
set([(5, 5)])
>>> for val in closed:
...   print val
... 
(5, 5)
relet
A: 

All your node object have to be hashable, see

http://docs.python.org/glossary.html#term-hashable

Quonux
+1  A: 

I do not have a problem running the code if node is a tuple, as you indicate. When I make node a list, e.g., node = [5,5], then I receive the error.

I believe the reason is because a list is mutable, so it is not suitable for checking for uniqueness:

   >>> a = [5,5] 
   >>> id(a) 
   140505526957552 
   >>> a.append(6) 
   >>> id(a)
   140505526957552

Since a has the same id despite the change, it cannot be used in a set.

beitar
+1  A: 

Show the actual code that you executed, plus the full traceback. Use copy/paste, don't type from memory. You should always do this. Even better reason in this case is that that error can happen only if node is a list, not a tuple as you have said.

John Machin
A: 

Are you sure you didn't typed node = [5, 5] instead of node = (5,5) ? Looks like you node is really a list and it rightly refuse to add a list to a set (as it is unhashable).

Again: with some fonts parenthesis and square brackets are very similar. Or stacks contains other data and you didn't showed the right node. But you can get the answer by yourself. Just do:

print type(node)

If it is a list you are here. If it is a tuple, something really weird occurred.

kriss
node is the output of stack.node = stack.pop()output = (5,5)
Shilpa
A: 

You can't hash a list because hashes must be immutable. The implementation of set requires this for efficiency. Since the elements of a list can be updated at any time, so would any hash value derived from the contents.

I think there's a mistake in your example, as it shows a tuple rather than a list.

Mark Ransom
thanks..i solved the problem
Shilpa