Ошибка typeerror unhashable type list

Автор оригинала: Team Python Pool.

Привет гики и добро пожаловать. В этой статье мы рассмотрим ошибку “unhashable type: list.” С этой ошибкой мы сталкиваемся при написании кода на Python. В этой статье наша главная цель – рассмотреть эту ошибку и устранить её. Всего этого мы добьемся на нескольких примерах. Но сначала давайте попробуем получить краткий обзор того, почему она возникает.

Словари Python принимают в качестве ключа только хэшируемые типы данных. Это означает что значения этих типов остаются неизменными в течение всего их времени жизни. Но когда мы используем тип данных list, который не является хэшируемым, мы получаем такую ошибку.

Ошибка “unhashable type: list”

В этом разделе мы рассмотрим причину, из-за которой возникает эта ошибка. Мы учтем все, что обсуждалось до сих пор. Давайте рассмотрим это на примере:

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

Выход:

TypeError: unhashable type: 'list'

Выше мы рассмотрели простой пример. Мы создали числовой словарь, а затем попытались распечатать его. Но вместо вывода мы получаем ошибку, потому что использовали в нем тип list в качестве ключа. В следующем разделе мы рассмотрим, как устранить эту ошибку.

Но прежде давайте рассмотрим еще один пример.

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

В приведенном выше примере мы сталкиваемся всё с той же проблемой. В этом словаре мы взяли в качестве данных количество государств и их рейтинг по всему миру. Теперь давайте быстро перейдем к следующему разделу и устраним эти ошибки.

Устранение ошибки “unhashable type:list”

В этом разделе мы постараемся избавиться от ошибки. Давайте начнем с первого примера. Чтобы исправить все это, мы должны использовать кортеж.

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

С помощью всего лишь небольшого изменения кода мы можем исправить ошибку. Здесь мы использовали кортеж, который является неизменяемым (hashable) типом данных. Аналогично мы можем исправить ошибку во втором примере.

country=[{
    "name": "India", tuple([28,7]): "states and area",
    "name": "France", tuple([27,48]): "states and area"
}]
print(country)
[{'name': 'France', (28, 7): 'states and area', (27, 48): 'states and area'}]

Опять же с помощью кортежа мы можем всё исправить. Это простая ошибка, и ее легко исправить.

Разница между hashable и unhashable типами данных

В этом разделе мы видим основное различие между двумя типами. Кроме того, мы классифицируем различные типы данных, которые мы используем при кодировании на python, под этими 2 типами.

В этом разделе мы видим основное различие между двумя типами данных. Кроме того, мы классифицируем различные типы данных, которые мы используем при кодировании в Python под этими двумя типами.

Хэшируемые Нехэшируемые
Для этого типа данных значение остается постоянным на всем протяжении жизни объекта. Для этого типа данных значение не является постоянным и изменяется по месту.
Типы данных, подпадающие под эту категорию: int, float, tuple, bool, string, bytes. Типы данных, подпадающие под эту категорию: list, set, dict, bytearray.

Заключение

В этой статье мы рассмотрели ошибку unhashable type: list. Мы рассмотрели, почему она возникает, и методы, с помощью которых мы можем её исправить. Чтобы разобраться в этом, мы рассмотрели несколько примеров. В конце концов, мы можем сделать вывод, что эта ошибка возникает, когда мы используем нехэшируемый (изменяемый) тип данных в словаре.

If you arrived at this post because you got the error in the title, apart from OP’s problem (where a list was being used a key to a dict), there are a couple more cases where this may occur.

1. A list is being passed into a set

Just like why lists cannot be dictionary keys, lists cannot be a set element. If a tuple is to be added to it, is shouldn’t contain a list either.

s = {(1, 2), [3, 4]}    # <---- TypeError: unhashable type: 'list'
s = {(1, 2), (3, 4)}    # <---- OK

s.add((5, [6]))         # <---- TypeError because the element to be added contains a list
s.add((5, 6))           # <---- OK because (5, 6) is a tuple
2. Pandas groupby on lists

Another common way this error occurs is if a pandas dataframe column stores a list and is used as a grouper in a groupby operation. A solution is similar as above, convert the lists into tuples and groupby using the column of tuples.

import pandas as pd
df = pd.DataFrame({'group': [[1, 2], [3, 4], [5, 6]], 'value': [0, 1, 2]})

# group  value
# [1, 2]     0
# [3, 4]     1
# [5, 6]     2

df.groupby('group')['value'].mean()                  # <---- TypeError
df.groupby(df['group'].agg(tuple))['value'].mean()   # <---- OK
#          ^^^^^^^^^^^^^^^^^^^^^^  <--- convert each list into a tuple
3. Pandas index/column labels contain a list

Pandas column label cannot be a list (because it is analogous to a dictionary key), so if you attempt to rename() it by a list, it will show this error. A solution is to convert the list into a tuple (or even into a MultiIndex).

df = pd.DataFrame({'group': range(3)})
df.rename(columns={'group': ['col', 'one']})               # TypeError
df.rename(columns={'group': ('col', 'one')})               # OK
df.columns = pd.MultiIndex.from_tuples([('col', 'one')])   # OK

Pandas index can contain a list as a value but if you try to index that row, it will throw this error. A solution is to convert the list into a tuple or simply «clean» the data (probably the index shouldn’t contain a list/tuple to begin with) such as converting it into a MultiIndex.

df = pd.DataFrame({'group': range(3)}, index=[['a'], 'b', 'c'])
df.loc['b']           # TypeError
4. collections.Counter is called on an object containing a list

Because Counter creates a dict-like object, each value should be immutable for the very same reason, so if an object contains a list, this error will be shown. A solution is probably to convert the list into a tuple

from collections import Counter
lst = ['a', 'b', ['c']]
Counter(lst)                  # TypeError

Counter(['a', 'b', ('c',)])   # OK

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!

In Python, a TypeError is raised when an operation or function is applied to an object of an inappropriate type. One such error is the “TypeError: unhashable type: ‘list’” error. This error occurs when we try to use a list (which is an unhashable type object) in a place that requires a hashable type. In this tutorial, we will discuss the reasons behind this error and how to fix it.

fix typeerror unshashable type list

Understanding the TypeError: unhashable type: 'list' error

In Python, hashable types are those which have a hash value that remains constant throughout its lifetime. Hash values are unique identifiers assigned to objects by Python’s built-in hash() function. These hash values are used to quickly compare and access objects in dictionaries and sets.

On the other hand, unhashable types are those which do not have a constant hash value and cannot be used as keys in dictionaries or elements in sets. Examples of unhashable types include lists, sets, and dictionaries themselves.

To illustrate the difference between hashable and unhashable types, consider the following example:

# Hashable type (tuple)
my_tuple = (1, 2, 3)
print(hash(my_tuple))

Output:

529344067295497451
# Unhashable type (list)
my_list = [1, 2, 3]
print(hash(my_list))

Output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[2], line 3
      1 # Unhashable type (list)
      2 my_list = [1, 2, 3]
----> 3 print(hash(my_list))

TypeError: unhashable type: 'list'

In the above example, we create a tuple my_tuple and a list my_list containing the same elements. When we try to hash the tuple using the built-in hash() function, we get a unique hash value. However, when we try to hash the list, we get a TypeError because lists are unhashable. This means that we cannot use lists as keys in dictionaries or elements in sets.

The TypeError: unhashable type: 'list' error occurs when we try to use a list in a place that requires a hashable type, for example, as a key to a dictionary or a value in a set. This error occurs because lists are mutable, which means that their contents can be changed. In Python, only immutable objects can be used as keys in a dictionary or as elements in a set. Here are some common scenarios in which this error occurs:

  • When we try to use a list as a key in a dictionary
  • When we try to use a list as an element in a set
# using a list as a key in a dictionary
my_dictionary = {
    "Name": "Jim",
    ["Age", "Department"]: [26, "Sales"]
}

Output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[3], line 2
      1 # using a list as a key in a dictionary
----> 2 my_dictionary = {
      3     "Name": "Jim",
      4     ["Age", "Department"]: [26, "Sales"]
      5 }

TypeError: unhashable type: 'list'

In the above example, we’re trying to use the list ["Age", "Department"] as a key in the dictionary my_dictionary. You can see that we get the TypeError: unhashable type: 'list'.

# using a list as a an element in a set
my_set = set([1, 2, 3])
my_set.add([4, 5])

Output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[4], line 3
      1 # using a list as a an element in a set
      2 my_set = set([1, 2, 3])
----> 3 my_set.add([4, 5])

TypeError: unhashable type: 'list'

In the above example, we’re trying to add the list [4, 5] as an element to the set my_set. Since lists are unhashable types, we get the error TypeError: unhashable type: 'list'.

Fixing the Error

To fix the TypeError: unhashable type: 'list', use a hashable type like a tuple instead of a list. For example, if you’re trying to use a list as a key in a dictionary, use a tuple instead. Similarly, if you’re trying to use a list as an element in a set, you can use a tuple or a frozen set instead.

Let’s revisit the examples from above and fix those errors.

# using a tuple as a key in a dictionary
my_dictionary = {
    "Name": "Jim",
    ("Age", "Department"): [26, "Sales"]
}

In the above example, we replaced the list ["Age", "Department"] with the tuple, ("Age", "Department") as a key in the dictionary. We don’t get an error on executing the above code. Notice that you can still use a list as a value in the dictionary but the keys must be hashable types.

# using a tuple as a an element in a set
my_set = set([1, 2, 3])
my_set.add((4, 5))

In the above example, we replaced the list [4, 5] with the tuple, (4, 5) as an element in the set. We don’t get an error on executing the above code.

In summary, you can take the following steps to fix the TypeError: unhashable type: 'list' error.

  1. Identify the code that is causing the error.
  2. Check if you are using a list as a key in a dictionary or as an element in a set.
  3. If you are using a list as a key in a dictionary, consider using a tuple instead. Tuples are immutable and can be hashed.
  4. If you are using a list as an element in a set, consider using a tuple instead.
  5. If you cannot use a tuple, consider using a different data structure that is immutable and can work as an adequate replacement for your list.

Conclusion

The “TypeError: unhashable type: ‘list’” error occurs when we try to use a list as a key in a dictionary or as an element in a set. This error can be fixed by converting the list into an immutable object such as a tuple, a string, or a frozenset. By following the steps mentioned in this tutorial, you can easily fix this error and make your code more efficient and error-free.

You might also be interested in –

  • How to Fix – TypeError: string indices must be integers
  • How to Fix – SyntaxError can’t assign to literal
  • How to Fix – SyntaxError can’t assign to operator
  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

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!

  • Ошибка typeerror numpy ndarray object is not callable
  • Ошибка traymenu exe при загрузке компа 007
  • Ошибка trapper b2fe5bad far cry 6
  • Ошибка trapper 1c07b734 far cry 5
  • Ошибка transport vmdb error 14 pipe connection has been broken