Python says “A list is not hash-able”:
Traceback (most recent call last):
File “listexperiments.py”, line 135, in
File “listexperiments.py”, line 82, in ParseDRCExperimentSpaceSpecs
g_drc_expspace[key] = 0;
TypeError: unhashable type: 'list'
There must be some deep reason under the unhashability of lists, but now, I need to hash a Java ArrayList, and the purpose is to determine whether two ArrayLists contain the same elements without actually having to walk through the list.
A duct-tape solution seems as trivial as the following:
Step 1: Prepare a function that takes into two integers and returns one, for example, XOR. The result of the XOR stores the information coming from its two inputs (it also may lose some information by mapping an 2^64-sized space to a 2^32-sized hash space).
Step 2: Keep feeding the Kth element and the number K into the input 1 of the function and its result into the input 2 of the function.
This approach seems to has measures on a sheet music pretty well.
So going back to the original question: Why does not Python allow hashing a List?
Need read StackOverflow.
I read StackOverflow; it turned out the Hash implementation depends on the `id' of an object. The `id' looked much like the `store' or the `memory address' of a `constant', much like the `constant string literal' in CPPGM PA8 that points to variable with a immutable type. The unhashability is based on the rule: “the id (location) of two mutable objects is irrelevant to whether their contents are identical, so a hash function based on the address of the store of an object can't work for mutable types”.
Mutable types in Python include dict, list and bytearray. They are easier to understand.
Immutable types in Python include tuple and str.
Immutables do not change; although the following statements seem to modify the storage of variables, they actually assign new instances to respective variable names:
a=”blah”; id(a); a=”bleh”; id(a);
139997263880864 // will have different hashes
139997263880816 // hash of b would be the same as hash of old a (“blah”)
It looks very much like taking the address of a constant string in C, which in turn is a const char* pointing to the read only data segment.
So far the explanation seems to be enough for explaining the cases I came across during my daily usage of Python.