TypeError: unhashable type: 'list'

The error message "TypeError: unhashable type: 'list' " typically indicates an attempt to employ a list as a hashable argument. Hashing an unhashable object leads to an error. For example, using a list as a dictionary key is infeasible since lists aren't hashable. The conventional resolution involves converting the list to a tuple.

example
my_dict = {'name': 'John', [1,2,3]:'values'} print(my_dict)
output What is Python: TypeError: unhashable type: 'list'

This error shows that the my_dict key [1,2,3] is List and List is not a hashable type in Python . Dictionary keys must be immutable types and list is a mutable type.

Fix: Cast list to a tuple

You'll have to change your list into tuples if you want to put them as keys in your dictionary .

my_dict = {'name': 'John', tuple([1,2,3]):'values'} print(my_dict)
output
{'name': 'John', (1, 2, 3): 'values'}

The hash() function is a built-in Python method utilized to generate a distinct numerical value. It can be employed with user-defined objects that remain unaltered after initialization. This characteristic finds significance primarily in the context of dictionary keys.

Examples of hashable objects:

int, float, decimal, complex, bool, string, tuple, range, frozenset, bytes

Examples of Unhashable objects:

list, dict, set, bytearray, user-defined classes

Tuple and List

While tuples might appear similar to lists, they frequently serve distinct roles and have different applications. Tuples are immutable and typically comprise a heterogeneous sequence of elements accessible through unpacking or indexing. In contrast, lists are mutable and generally consist of homogeneous elements accessed by iteration.

Python Tuple and List

Hashing

Hashing is a fundamental concept in computer science that facilitates the creation of efficient, pseudo-random access data structures for rapid storage and retrieval of substantial data. Immutable objects, those that remain unmodifiable, are deemed hashable, possessing an unchanging unique value. A hashing function takes an object, such as the string "Java," and produces a consistent, fixed-size code—typically an integer.

Conclusion

The "TypeError: unhashable type: 'list'" error occurs when attempting to use a list as a hashable object. Lists are mutable and lack the properties necessary for reliable hashing, making them unsuitable as dictionary keys or elements in sets. To resolve this, consider using tuples, which are immutable and can serve as hashable alternatives in such contexts.