Python typeerror unhashable type list

TypeError: unhashable type: ‘list’

This error occurs when you try to use a list as key in the dictionary or set. As you know ‘list’ is an unhashable object that can not be used as a key for any dictionary or set.

In simple terms, this error occurs when you try to hash a ‘list’, which is an unhashable object.

Example 1: Using ‘list’ as key in a dictionary

my_dictionary = print('Dictionary :',my_dictionary)
TypeError: unhashable type: 'list'

To fix this error, you can convert the ‘list’ into a hashable object like ‘tuple’ and then use it as a key for a dictionary as shown below

Correct Code

my_dictionary = print('Dictionary :',my_dictionary)

Example 2: Using list as key in a set

mylist = [1,2,[3,4],5,6,7,8,9] myset = set(mylist) print('Set :',myset)
TypeError: unhashable type: 'list'

To fix this error, you can convert the ‘list’ into a hashable object like tuple then use it as a key for ‘set’ as shown below:

mylist = [1,2,tuple([3,4]),5,6,7,8,9] myset = set(mylist) print('Set :',myset)

What is Hashing in Python

In python, hashing is the method of encoding the data into a fixed-size integer which represent the original value. You can hash only those objects which are hashable or objects that can’t be altered.

Hashable objects in Python

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

Unhashable objects in Python

list, dict, set, bytearray, user-defined classes
  • Learn Python Programming
  • Python Online Compiler
  • Python Training Tutorials for Beginners
  • Square Root in Python
  • Addition of two numbers in Python
  • TypeError: ‘int’ object is not subscriptable
  • pip is not recognized
  • Python Comment
  • Python Continue Statement
  • Python String Replace
  • Polymorphism in Python
  • Inheritance in Python
  • Python zip()
  • Bubble Sort in Python
  • Python slice() function
  • Python list append and extend
  • Python Sort Dictionary by Key or Value
  • indentationerror: unindent does not match any outer indentation level in Python
  • Python KeyError
  • Pangram Program in Python
  • Tutorials
  • Learn Python Programming
  • Python Online Compiler
  • Python Training Tutorials for Beginners
  • Square Root in Python
  • Addition of two numbers in Python
  • Null Object in Python
  • Python vs PHP
  • TypeError: ‘int’ object is not subscriptable
  • pip is not recognized
  • Python Comment
  • Python Min()
  • Python Factorial
  • Python Continue Statement
  • Armstrong Number in Python

#3940 Sector 23,
Gurgaon, Haryana (India)
Pin :- 122015

  • Write for us
  • Career Guidance Tool
  • SAP Transaction Codes
  • Sample Resume
  • Institutes
  • SAP PDF Books
  • Classifieds
  • Recent Articles
  • Contact Us
  • About Us
  • Terms of Use
  • Privacy Policy
  • Cookies Policy
Читайте также:  Верхнее поле в html

Источник

Как решить ошибку “unhashable type: list” в Python

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

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

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

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

TypeError: unhashable type: 'list'

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

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

TypeError: unhashable type: 'list'

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

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

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

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

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

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

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

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

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

Заключение

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

Читайте ещё по теме:

Источник

How to Handle Unhashable Type List Exceptions in Python

How to Handle Unhashable Type List Exceptions in Python

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.

Читайте также:  Python if function returns nothing

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

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:

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 my_dict = 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:

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:

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!

Источник

How to Solve Python TypeError: unhashable type: ‘list’

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?

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.

Читайте также:  Python create new project

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)

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:

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:

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!

Share this:

Источник

Оцените статью