Handle Unhashable Type List Exceptions in Python
Last Updated :
26 Feb, 2024
Python, with its versatile and dynamic nature, empowers developers to create expressive and efficient code. However, in the course of Python programming, encountering errors is inevitable. One such common challenge is the “Unhashable Type List Exception“. In this article, we will dive deep into the intricacies of Unhashable Type List Exception in Python. We will explore why this exception occurs and How to effectively handle them.
What is Unhashable Type List Exceptions In Python?
In Python programming, a Hashable object is something which is having a hash value. Hashable objects are immutable and cannot be modified after initialization. Similarly, unhashable objects do not have hash values such as list, dict, set, etc.
Why do Unhashable Type List Exceptions In Python occur?
Below are some of the reasons why Unhashable Type List Exception occurs in Python:
Initialize List as Key in Dictionary
In this example, we are using a list as a key in a dictionary that leads to an Unhashable Type List Exception in Python.
Python3
l = [ 'a' ]
dictionary = {l: 1 }
print (dictionary)
|
Output:
Error: Traceback (most recent call last):
File "<string>", line 3, in <module>
TypeError: unhashable type: 'list'
Initialize List as Set
In this example, we are adding a list inside a set that is not possible and leads to Unhashable Type List Exception in Python.
Python3
l = [ 'a' ]
s = set ()
s.add(l)
print (s)
|
Output:
Error: Traceback (most recent call last):
File "<string>", line 8, in <module>
TypeError: unhashable type: 'list'
Handling Unhashable Type List Exceptions In Python
Below are some of the ways to handle Unhashable Type List Exceptions in Python:
- Convert List to Tuple
- Convert List to JSON Strings
Convert List to Tuple
We can convert the list to the corresponding tuple value and can further use it as the key for the dictionary or the element for the set.
Python
l = [ 'a' ]
dictionary = { tuple (l): 1 }
print (dictionary)
s = { tuple (l)}
print (s)
|
Output
{('a',): 1}
set([('a',)])
Convert List to JSON Strings
The idea is to convert the list to the JSON and can further use it as the key for the dictionary or the element for the set.
Python
import json
l = [ 'a' ]
dictionary = {json.dumps(l): 1 }
print (dictionary)
s = {json.dumps(l)}
print (s)
|
Output
{'["a"]': 1}
set(['["a"]'])
Share your thoughts in the comments
Please Login to comment...