Unhashable type list error

The error TypeError: unhashable type: 'list' occurs when trying to get a hash of a list. For example, using a list as a key in a Python dictionary will

The error TypeError: unhashable type: ‘list’ occurs when trying to get a hash of a list. For example, using a list as a key in a Python dictionary will throw the TypeError because you can only use hashable data types as a key.

To solve this error, you can cast the list to a tuple, which is hashable.

This tutorial will go through the error in detail and how to solve it with the help of code examples.


Table of contents

  • TypeError: unhashable type: ‘list’
    • What Does TypeError Mean?
    • What Does Unhashable Mean?
  • Example #1: Using a List as a Key in a Dictionary
    • Solution
  • Example #2: Using a List as a Value in a Set
    • Solution #1: Cast List to Tuple
  • Summary

TypeError: unhashable type: ‘list’

What Does TypeError Mean?

TypeError occurs whenever you try to perform an illegal operation for a specific data type object. In the example, the illegal operation is hashing, and the data type is List.

What Does Unhashable Mean?

By definition, a dictionary key needs to be hashable. An object is hashable if it has a hash value that remains the same during its lifetime. A hash value is an integer Python uses to compare dictionary keys while looking at a dictionary.

When we add a new key:value pair to a dictionary, the Python interpreter generates a hash of the key.

Similarly, we can think of a set as a dictionary that just contains the keys, so it also requires hashable items.

We can only hash particular objects in Python, like strings or integers. All immutable built-in objects in Python are hashable, for example, tuple, and mutable containers are not hashable, for example, list.

Example #1: Using a List as a Key in a Dictionary

Let’s look at an example where we define a dictionary. The first two keys are strings, the third key is a list of strings, and the values are integers.

name_list = ["Tim", "Lisa"]

a_dict = {
   "Alex": 2,
   "Holly":4,
   name_list:6
}

print(a_dict)

If we try to create the dictionary, we will get the following error:

TypeError                                 Traceback (most recent call last)
----≻ 1 a_dict = {
      2 "Alex": 2,
      3 "Holly":4,
      4 name_list:6
      5 }

TypeError: unhashable type: 'list'

This error occurs because only hashable objects can be a key in a dictionary, and lists are not hashable objects.

Solution

To solve this error, we can cast the list to a tuple before using it as a dictionary, using the built-in tuple() method. Let’s look at the revised code:

name_list = ["Tim", "Lisa"]

a_dict = {

   "Alex": 2,

   "Holly":4,

   tuple(name_list):6

}

print(a_dict)
{'Alex': 2, 'Holly': 4, ('Tim', 'Lisa'): 6}

You can also unpack the list into its elements and use those objects as keys. Let’s look at the revised code:

name_list = ["Tim", "Lisa"]

key3, key4 = name_list

a_dict = {

   "Alex": 2,

   "Holly":4,

   key3:6,

   key4:6

}

print(a_dict)

In this example, we set the value for the keys ‘Tim’ and ‘Lisa’ to 6. Let’s run the code to see the result:

{'Alex': 2, 'Holly': 4, 'Tim': 6, 'Lisa': 6}

Example #2: Using a List as a Value in a Set

If we try to cast a list to a set and one of the values in the list is itself a list, we will throw the TypeError. Let’s look at a code example:

a_list = [1, 2, [3, 4], 5, 6]

a_set = set(a_list)

print(a_set)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
----≻ 1 a_set = set(a_list)

TypeError: unhashable type: 'list'

This error occurs because sets require their items to be hashable. Only the immutable types like numbers are hashable out of the predefined Python types. But the list [3, 4] is mutable, so we cannot include it in the set.

Solution #1: Cast List to Tuple

We can cast the list item to a tuple before casting the full list to a set to solve this error. Let’s look at the revised code:

a_list = [1, 2, tuple([3, 4]), 5, 6]

a_set = set(a_list)

print(a_set)

Let’s run the code to get the result:

{1, 2, 5, (3, 4), 6}

Summary

Congratulations on reading to the end of this article! The error: TypeError: unhashable type: ‘list’ occurs when trying to get the hash value of a list.

If you want to get the hash of a container object, you should cast the list to a tuple before hashing.

For further reading on TypeError with unhashable data types, go to the article: How to Solve Python TypeError: unhashable type: ‘numpy.ndarray’.

Go to the Python online courses page to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

The Python TypeError: unhashable type: 'list' usually means that a list is being used as a hash argument. This error occurs when trying to hash a list, which is an unhashable object. For example, using a list as a key in a Python dictionary will cause this error since dictionaries only accept hashable data types as a key.

The standard way to solve this issue is to cast a list to a tuple, which is a hashable data type.

Install the Python SDK to identify and fix these undefined errors

Tuples vs Lists

Tuples are similar to lists but are immutable. They usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing. On the other hand, lists are mutable and contain a homogeneous sequence of elements that are accessed by iterating over the list.

Immutable objects such as tuples are hashable since they have a single unique value that never changes. Hashing such objects always produces the same result, so they can be used as the keys for dictionaries.

TypeError: Unhashable Type: ‘List’ Example

Here’s an example of a Python TypeError: unhashable type: 'list' thrown when a list is used as the key for a dictionary:

my_dict = {1: 'Bob', [2,3,4]: 'names'}
print(my_dict)

Since a list is not hashable, running the above code produces the following error:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    my_dict = {1: 'Bob', [2,3,4]: 'names'}
TypeError: unhashable type: 'list'

How to Fix TypeError: unhashable type: ‘list’

The Python TypeError: Unhashable Type: 'List' can be fixed by casting a list to a tuple before using it as a key in a dictionary:

my_dict = {1: 'Bob', tuple([2,3,4]): 'names'}
print(my_dict)

In the example above, the tuple() function is used to convert the list to a tuple. The above code runs successfully, produces the following output:

{1: 'Bob', (2, 3, 4): 'names'}

Frequently Asked Questions

What are Unhashable Type Errors in Python?

Unhashable type errors appear in a Python program when a data type that is not hashable is used in code that requires hashable data. An example of this is using an element in a set or a list as the key of a dictionary.

What is Hashable in Python?

Hashable is a feature of Python objects that determines whether the object has a hash value or not. An object is hashable if it has a hash value that doesn’t change during its lifetime. A hashable object can be used as a key for a dictionary or as an element in a set.

All built-in immutable objects, like tuples, are hashable while mutable containers like lists and dictionaries are not hashable.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Hello geeks, and welcome in this article, we will be covering “unhashable type: list.” It is a type of error that we come across when writing code in python. In this article, ur main objective is to look at this error. Along with that, we will also try to troubleshoot and get rid of this error. We will achieve all this with a couple of examples. But first, let us try to get a brief overview of why this error occurs.

Python dictionaries only accept hashable data-types as a key. Here the hashable data-types means those values whose value remains the same during the lifetime. But when we use the list data-type, which is non-hashable, we get this kind of error.

The error-“unhahasble type: list”

In this section, we will look at the reason due to which this error occurs. We will take into account everything discussed so far. Let us see this through an example:

numb ={ 1:'one', [2,10]:'two and ten',11:'eleven'}
print(numb)

Output:

TypeError: unhashable type: 'list'

Here above, we have considered a straightforward example. Here we have used a dictionary to create a number dictionary and then tried to print it. But instead of the output, we get an error because we have used a list type in it. In the next section, we will see how to eliminate the error.

But Before that let us also look at an another example.

country=[
    {
    "name":"USA",[50,4]:"states and area",
    "name":"France",[27,48]:"states and area"}
]
print(country)
TypeError: unhashable type: 'list'

Here in the above example, we can see we come across the same problem. Here in this dictionary, we have taken the number of states and their ranking worldwide as the data. Now let’s quickly jump to the next section and eliminate these errors.

Troubleshooting:”unhashable type:list”

In this section, we will try to get rid of the errors. Let us start with the first example here. To rectify it all, we have to do is use a tuple.

numb ={ 1:'one', tuple([2,10]):'two and ten',11:'eleven'}
print(numb)
{1: 'one', (2, 10): 'two and ten', 11: 'eleven'}

With just a slight code change, we can rectify this. Here we have used a tuple, which is a hashable data data-type. Similarly, we can rectify the second error of the second example.

country=[
    {
    "name":"USA",tuple([50,4]):"states and area",
    "name":"France",tuple([27,48]):"states and area"}
]
print(country)
[{'name': 'France', (50, 4): 'states and area', (27, 48): 'states and area'}]

Again with the help of tuple we are able to rectify it. It is a simple error and can be rectified easily.

Difference between hashable and unhashable type

In this section, we see the basic difference between the 2 types. Also, we classify the various data-types that we use while coding in python under these 2 types.

Hashable Unhashable
For this data-type, the value remains constant throughout. For this data-type, the value is not constant and change.
Some data types that fall under this category are- int, float, tuple, bool, string, bytes. Some data types that fall under this category are- list, set, dict, bytearray.

CONCLUSION

In this article, we covered unhashable type: list error. We looked at why it occurs and the methods by which we can rectify it. To achieve it, we looked at a couple of examples. In the end, we can conclude that this error arises when we use an unhashable data-type in a dictionary.

I hope this article was able to clear all doubts. But in case you have any unsolved queries feel free to write them below in the comment section. Done reading this why not read about the cPickle module.

TypeError: unhashable type: ‘list’ error occurs mainly when we use any list as a hash object. As you already know list is a mutable Python object. For hashing an object it must be immutable like tuple etc. Hence converting every mutable object into immutable is the fix for the error TypeError: unhashable type: ‘list’.

There are a few python objects which are not hashable like dict, list, byte array, set, user-defined classes, etc.  When any of these objects come at the place where we treat them as a hashable object this error occurs.  This article will show you different scenarios for this bug with their fix.

let’s see a common scenario for this error.

Case 1: List as a dictionary key –

In order to demonstrate, We will create a dummy_dict. We can reproduce this error when we use any list a key in the dummy_dict. See the below example.

TypeError unhashable type list in dict

TypeError unhashable type list dict

The fix for the above error is to convert( typecasting) the list into the tuple and insert it into the dict as the key. A tuple is an immutable object. Let’s see the above code after fixing it.

sample_list=["C","D"]
dummy_dict={
    "A": 1,
    "B":2,
    tuple(sample_list):3

}
print(dummy_dict)

Here is the output.

{'A': 1, 'B': 2, ('C', 'D'): 3}

Case 2: Converting a nested list into the set (python convert list to set unhashable) –

When we typecast a nested list object directly into the set object. This error occurs.

unhashable type nested list into set

unhashable type nested list into a set

Like above, We can convert the nested list into the tuple. After it, we can easily convert the outer list into a set python object. Refer to the below code for better understanding.

 a = [11,23,34,tuple([51,65]),89]
 set(a)

below is the output for the code.

{(51, 65), 11, 23, 34, 89}

Case 3: Using hash() function with unhashable objects –

As you know that dict, list, byte array, set, user-defined classes, etc are unhashable objects in python. When we try to use them as a parameter in the hash function. We get the same error.

hash() function with unhashable object

hash() function with unhashable object

We can get the correct hash value of the above object by converting the list into the tuple object.

hash(tuple([1,2,3]))

Here is the hash value of the object after the conversion.

2528502973977326415

Again the center point for this error is to understand the basic difference between hashable and unhashable object. See the bottom line is if the value remain fix throughout then it is hashable object otherwise not. In addition the solution for typeerror unhashable type ‘list’ pandas or other kind of similar problems are also the same.

Similar Typeerrors :

1. Typeerror list object is not callable : Quick Fix for You

2.Typeerror nonetype object is not subscriptable : How to Fix ?

3.Typeerror nonetype object is not iterable : Complete Solution

Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

The TypeError: unhashable type: ‘list’ error occurs when you try to add a list as a key in a dictionary or as an item in a python Set. A hashable object is used as a key in the dictionary. The list is an unhashable type object that you’ve been trying to store. If an unhashable type object is tried to hash, the error TypeError: unhashable type: ‘list’ is thrown. The python set and dictionary uses hash algorithm to create a hash key which is used to get data quickly.

The list is a mutable object which can be modified at any time. If the list is modified after the hash key has been generated, then, the hash algorithm can not recognize the list. Hence the objects that are mutable are not hashable. If a list is passed as a hash argument, then it will throw the error TypeError: unhashable type: ‘list’.

Exception

This will show the stack trace of the error as below. The  TypeError: unhashable type error is shown as

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 1, in <module>
    a = {1, [2,3] , 4}
TypeError: unhashable type: 'list'
[Finished in 0.1s with exit code 1]

How to reproduce this issue

The python list is an object which is not hashable. In python, create a list object. Add the list into a set object. Or, add the list object as a key in the python dictionary. Since the unhashable object is not permitted in set or dictionary key, the error will be thrown.

test.py

a = {1, [2,3] , 4}
print a

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 1, in <module>
    a = {1, [2,3] , 4}
TypeError: unhashable type: 'list'
[Finished in 0.1s with exit code 1]

Root Cause

The set or dictionary uses hashing algorithm to store and retrieve the elements in the data structure. The set maintains the unique objects with hash code. The dictionary maintains the unique keys to store values. The list is an unhashable object that can be modified at any given time. The error TypeError: unhashable type: ‘list’ is due to the addition of an unhashable object to the set or dictionary key.

Solution 1

The unhashable object list can be stored in the dictionary after the list is converted to tuple. The tuple is a immutable object that can be stored in dictionary or set. The tuple() function is used to convert the list to a tuple. This will resolve the python error “TypeError: unhashable type: ‘list’”

test.py

a = {1, tuple([2,3]) , 4}
print a

Output

set([1, (2, 3), 4])
[Finished in 0.1s]

Solution 2

The python error “TypeError: unhashable type: ‘set’” is thrown if the set is added as a key in the dictionary. The set isn’t an immutable object. If the set object is to be converted as a tuple before it is added to the dictionary. This will resolve the “TypeError: unhashable type: ‘set’” error.

Example

a = {1:2, tuple([2,3]):3 , 4:4}
print a

Output

{1: 2, (2, 3): 3, 4: 4}
[Finished in 0.1s]

Solution 3

The another option to add the list in a dictionary is to store as value. The example below illustrates how to add a list into a dictionary as a value. In a dictionary the mutable objects can be stored as a value

Example

a = {'a':1, 'b':[2,3] , 'c':4}
print a

Output

{'a': 1, 'c': 4, 'b': [2, 3]}
[Finished in 0.0s]

Have you ever seen the message “TypeError: unhashable type” when running your Python program? Do you know what to do to fix it?

The message “TypeError: unhashable type” appears in a Python program when you try to use a data type that is not hashable in a place in your code that requires hashable data. For example, as an item of a set or as a key of a dictionary.

This error can occur in multiple scenarios and in this tutorial we will analyse few of them to make sure you know what to do when you see this error.

Let’s fix it now!

To understand when this error occurs let’s replicate it in the Python shell.

We will start from a dictionary that contains one key:

>>> country = {"name": "UK"}
>>> country
{'name': 'UK'} 

Now add a second item to the dictionary:

>>> country["capital"] = "London"
>>> country
{'name': 'UK', 'capital': 'London'} 

All good so far, but here is what happens if by mistake we use another dictionary as key:

>>> info = {"language": "english"}
>>> country[info] = info["language"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict' 

The error unhashable type: ‘dict’ occurs because we are trying to use a dictionary as key of a dictionary item. By definition a dictionary key needs to be hashable.

What does it mean?

When we add a new key / value pair to a dictionary, the Python interpreter generates a hash of the key. To give you an idea of how a hash looks like let’s have a look at what the hash() function returns.

>>> hash("language")
-79422224077228785
>>> hash({"language": "english"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict' 

You can see that we got back a hash for a string but when we tried to pass a dictionary to the hash function we got back the same “unhashable type” error we have seen before.

The unhashable type: ‘dict’ error is caused by the fact that mutable objects like dictionaries are not hashable.

Unhashable Type ‘numpy.ndarray’ Python Error

Let’s have a look at a similar error but this time for a numpy.ndarray (N-dimensional array).

>>> import numpy as np
>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> type(x)
<class 'numpy.ndarray'> 

After defining an array using NumPy, let’s find out what happens if we try to convert the array into a set.

>>> set(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray' 

We see the “unhashable type” error again, I want to confirm if once again we see the same behaviour when we try to apply the hash() function to our ndarray.

>>> hash(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray' 

The error is exactly the same, but why are we seeing this error when converting the array into a set?

Let’s try something else…

The array we have defined before was bi-dimensional, now we will do the same test with a uni-dimensional array.

>>> y = np.array([1, 2, 3]) 
>>> y
array([1, 2, 3])
>>> type(y)
<class 'numpy.ndarray'>
>>> set(y)
{1, 2, 3} 

It worked this time.

The reason why the first conversion to a set has failed is that we were trying to create a set of NumPy arrays but a NumPy array is mutable and hence it cannot be used as element of a set.

>>> my_set = {np.array([1, 2, 3]), np.array([4, 5, 6])}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray' 

The items in a set have to be hashable. Only immutable types are hashable while mutable types like NumPy arrays are not hashable because they could change and break the lookup based on the hashing algorithm.

For example, strings are immutable so an array of strings should get converted to a set without any errors:

>>> z = np.array(['one', 'two', 'three'])
>>> type(z)
<class 'numpy.ndarray'>
>>> set(z)
{'one', 'two', 'three'} 

All good. The same behaviour we have seen also applies to normal Python lists instead of NumPy arrays.

Unhashable Type ‘Slice’ Error in Python

The error unhashable type: ‘slice’ occurs if you try to use the slice operator with a data type that doesn’t support it.

For example, you can use the slice operator to get a slice of a Python list.

But what happens if you apply the slice operator to a dictionary?

Let’s find out…

>>> user = {"name": "John", "age": 25, "gender": "male"}
>>> user[1:3]
Traceback (most recent call last):
  File "", line 1, in 
    user[1:3]
TypeError: unhashable type: 'slice'         

The slice works on indexes and that’s why it works on lists and it doesn’t work on dictionaries.

Dictionaries are made of key-value pairs and this allows to access any value by simply using the associated dictionary key.

>>> user["name"]
'John'
>>> user["age"]
25

Unhashable Type ‘List’ in Python

Here is when you can get the unhashable type ‘list’ error in Python…

Let’s create a set of numbers:

>>> numbers = {1, 2, 3, 4}
>>> type(numbers)
<class 'set'> 

All good so far, but what happens if one of the elements in the set is a list?

>>> numbers = {1, 2, 3, 4, [5, 6]}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list' 

We get back the unhashable type error, and that’s because…

The items of a Python set have to be immutable but a list is mutable. This is required because the items of a set need to be hashable and a mutable data type is not hashable considering that its value can change at any time.

The tuple is similar to a list but is immutable, let’s see if we can create a set a provide a tuple instead of a list as one of its items:

>>> numbers = {1, 2, 3, 4, (5, 6)}
>>> numbers
{1, 2, 3, 4, (5, 6)} 

No error this time.

The difference between a list and a tuple in Python is that a list is mutable, is enclosed in square brackets [ ] and is not hashable. A tuple is immutable, is enclosed in parentheses () and is hashable.

Unhashable Type ‘Set’ Python Error

It’s time to find out how you can also encounter the unhashable type error when trying to use a set as item of another set.

First of all let’s define a list of sets:

>>> numbers = [{1, 2}, {3, 4}]
>>> numbers
[{1, 2}, {3, 4}]
>>> type(numbers[0])
<class 'set'> 

It works fine because the elements of a list can be mutable.

Now, instead of defining a list of sets we will try to define a set of sets.

Start by creating an empty set:

>>> numbers = set()
>>> type(numbers)
<class 'set'> 

Then we will use the set add method to add a first item of type set to it.

>>> item = {1,2}
>>> type(item)
<class 'set'>
>>> numbers.add(item)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set' 

We get back the error unhashable type: ‘set’ because, as explained before, the items of a set have to be immutable and hashable (e.g. strings, integers, tuples).

As a workaround we can use a different datatype provided by Python: the frozenset.

The frozenset is an immutable version of the Python set data type.

Let’s convert the item set to a frozenset:

>>> item
{1, 2}
>>> type(item)
<class 'set'>
>>> frozen_item = frozenset(item)
>>> type(frozen_item)
<class 'frozenset'> 

And now add the frozenset to the empty set we have defined before:

>>> numbers
set()
>>> numbers.add(frozen_item)
>>> numbers
{frozenset({1, 2})} 

It worked!

Hash Function For Different Data Types

We have seen that the unhashable type error occurs when we use a data type that doesn’t support hashing inside a data structure that requires hashing (e.g. inside a set or as a dictionary key).

Let’s go through several Python data types to verify which ones are hashable (they provide a __hash__ method).

Mutable data types are not hashable: list, set, dictionary.

>>> my_list = []
>>> print(my_list.__hash__)
None

>>> my_set = set()
>>> print(my_set.__hash__)
None

>>> my_dict = {}
>>> print(my_dict.__hash__)
None 

As you can see above, all three data types don’t provide the __hash__ method (None returned).

Immutable data types are hashable: string, integer, float, tuple, frozenset.

>>> my_string = ''
>>> print(my_string.__hash__)
<method-wrapper '__hash__' of str object at 0x7ffc1805a2f0>

>>> my_integer = 1
>>> print(my_integer.__hash__)
<method-wrapper '__hash__' of int object at 0x103255960>

>>> my_float = 3.4
>>> print(my_float.__hash__)
<method-wrapper '__hash__' of float object at 0x7ffc0823b610>

>>> my_tuple = (1, 2)
>>> print(my_tuple.__hash__)
<method-wrapper '__hash__' of tuple object at 0x7ffc08344940>

>>> my_frozenset = frozenset({1, 2})
>>> print(my_frozenset.__hash__)
<method-wrapper '__hash__' of frozenset object at 0x7ffc0837a9e0> 

All these data types have an implementation of the __hash__ function, they are hashable.

Conclusion

We have seen several circumstances in which the unhashable type error can occur in your Python code.

Specific Python data types require hashable data, for example the items of a set have to be hashable or the keys of a Python dictionary have to be hashable.

If unhashable data is used where hashable data is required the unhashable type error is raised by the Python interpreter.

You now know how to find out the cause of the error and how to solve it potentially by replacing a Python data type that is unhashable with a data type that is hashable.

Related posts:

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Понравилась статья? Поделить с друзьями:
  • Unhandled rejection error etelegram 400 bad request wrong file identifier http url specified
  • Unhandled rejection error etelegram 400 bad request message text is empty
  • Unhandled promise rejection syntaxerror json parse error unexpected identifier object
  • Unhandled php plugin error call the php plugin vendor
  • Unhandled exception произошла одна или несколько ошибок фазмофобия