To solve TypeError: unhashable type: ‘list’ when using built-in set function error follow below methods.
ERROR LOG
TypeError: unhashable type: ‘list’
How to solve TypeError: unhashable type: ‘list’ when using built-in set function ?
The error message TypeError: unhashable type: ‘list’ usually indicates that you are attempting to use a list as a hash parameter. This means that attempting to hash an un-hashable object will result in an error. For example, using a list as a key in the dictionary is not possible because lists cannot be hashed. The conventional solution to this problem is to cast a list to a tuple.
Example:
my_dict = {'marks': 98, [4,5,6]:'values'}
print(my_dict)
Output:
TypeError Traceback (most recent call last)
<ipython-input-2-33e10539cd92> in <module>()
----> 1 my_dict = {'marks': 98, [4,5,6]:'values'}
2 print(my_dict)
TypeError: unhashable type: 'list'
This error shows that the my_dict key [4,5,6] is List
and List is not a hashable type in Python .
Solution : Cast list to a tuple
By changing the given list into a tuple we can solve the issue. i.e.,
my_dict = {'marks': 98, tuple([4,5,6]):'values'}
print(my_dict)
Output:
{‘marks’: 98, (4, 5, 6): ‘values’}
The hash() function is a built-in Python method that returns a unique number. This can be applied to any user-defined object that will not be altered once it has been initialized. This feature is mostly utilized in dictionary keys.
Examples of hashable objects:
int, float, decimal, complex, bool, string, tuple, range, frozenset, bytes
Examples of Unhashable objects:
user-defined classes, list, dict and set
Hope the above solution works.
Also read : Python error: “IndexError: string index out of range”