[Tutor] how to understand unhashable type: 'list'

Steven D'Aprano steve at pearwood.info
Thu Nov 17 15:09:58 CET 2011

lina wrote:

> May I ask which role the __repr__ plays here?
> ...       weight[elem.__repr__()] += 1
>> ...   else:
>> ...       weight[elem.__repr__()] = 1
>> ...

You should never call elem.__repr__(), any more than you would call 
elem.__len__() or elem.__str__().

(Well, technically there *are* rare uses for calling such double 
underscore special methods directly, but this is not one of them!)

Instead, you should call repr(elem), len(elem), str(elem).

The purpose here is to convert the sublist, elem, which is unhashable, 
into something which is hashable. Strings are hashable, and so if you 
use repr() to convert it into a string, you can use it in a dictionary.

I don't see any advantage to using repr() instead of str(). Given the 
data you are working with, there is no difference:

py> str([['1', '2'], ['33', '44']])
"[['1', '2'], ['33', '44']]"
py> repr([['1', '2'], ['33', '44']])
"[['1', '2'], ['33', '44']]"

In my opinion, turning objects into strings unnecessarily is not good 
practice. Better to use a tuple than a string.


More information about the Tutor mailing list