S there any specific reason why to use a list as a key

Is there any specific reason why to use a list as a key would be a problem?

Can you elaborate on your question, please?

A list cannot be a key, but it can be a value. Keys are either str or number.

>>> a = {3.14: 'pi'}
>>> a
{3.14: 'pi'}
>>> a[3.14]
>>> b = {22/7: 'pi approx.'}
>>> b
{3.142857142857143: 'pi approx.'}
>>> b[22/7]
'pi approx.'
>>> import math
>>> c = {'pi': math.pi}
>>> c['pi']

As far as I can tell, it has to do with mu/immutability and un/hashable properties of objects.

For example, a list is a mutable object, which means the values assigned to it can be changed - so it cannot have a unique hash value (identifier). A string is an immutable object, so its values never change - therefore it can have an unique hash value. With the hash function it is possible to test if objects are equal, even if they are not of the same type - so you can see the importance of the values attributed to objects. An advantage of this is that looking up values in dictionaries is much faster than iterating through a list, since Python uses the hash values (unique) and ends up cutting the time needed to execute the task.

How does this apply to dictionaries keys?
Again, as far as I can tell, the keys in dic play the part of indexes in lists. You can change the value assigned to index “0”, but you cannot change the index itself. Since dictionaries are unordered (in terms numeric or alphabetic order), something has to ground the value to keep it reachable - that is what the key does.

These might help:
What does hash do in python?
Python hash()

1 Like