0

Im trying to hash an object of a custom class using the

hash()

function. My code does the following within the class

def __hash__(self):
    return hash(tuple(self.somelistattribute))

Where the attribute somelistattribute is list of lists such as:

Why do i keep getting an error:

TypeError: unhashable type: 'list'

How do I fix it?

2 Answers 2

3

Because list is unhashable, and that includes the sublists. To convert the sublists, use map():

    return hash(tuple(map(tuple, self.somelistattribute)))
Sign up to request clarification or add additional context in comments.

16 Comments

I tried this, I get the same error. I forgot to mention that the it is not a list of lists of integers, but a list os lists of strings. Does that change anything?
Would you mind giving an example that reproduces the problem?
You mean the class constructor? or where I'm specifically encountering the problem?
I mean the list of lists that can't be pickled. A list of lists of strings when converted to a tuple of tuples of strings doesn't have any lists that can't be pickled. I'd like an example of your list.
[["", "", "", "", ""],["", "", "", "", ""],["", "", ".", "", ""], ["", "", "", "", ""],["", "", "", "", ""]]
|
0

The problem is the lists inside of your outer list. Those aren't hashable, and calling tuple() only changes the outer list to a tuple.

You can fix this in a few ways, like with map():

hash(tuple(map(tuple, list_of_lists)))

or with a comprehension:

hash(tuple(tuple(x) for x in list_of_lists))

4 Comments

I tried this, it doesn't work and i encounter the same problem
@SrikanthSrinivas then please edit your question to contain code that demonstrates the problem. The code in your question works perfectly fine with the answers you've been given so far.
@SrikanthSrinivas and that changed nothing; the answers here still work perfectly fine for the example in your question.
@DanGetz: By the way, the [edit] shortcut link is for the post under which it is used. In this case, your link is for editing your answer.

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.