Net-informations.com
SiteMap  | About    

TypeError: unhashable type: 'list'



TypeError: unhashable type: 'list' usually means that you are trying to use a list as an hash argument. This means that when you try to hash an unhashable object it will result an error. For ex. when you use a list as a key in the dictionary , this cannot be done because lists can't be hashed. The standard way to solve this issue is to cast a list to a tuple .

What is Python: TypeError: unhashable type: 'list'

example

output

This error shows that the my_dict key [1,2,3] is List and List is not a hashable type in Python . Dictionary keys must be immutable types and list is a mutable type.

Fix: Cast list to a tuple

You'll have to change your list into tuples if you want to put them as keys in your dictionary .

output

The hash() is a built-in python method, used to return a unique number . This can be applied to any user-defined object which won’t get changed once initialized. This property is used mainly in dictionary keys .

Examples of hashable objects:

Examples of Unhashable objects:

Tuple and List

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable , and usually contain an heterogeneous sequence of elements that are accessed via unpacking or indexing . Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

Python Tuple and List

Hashing

Hashing is a concept in computer science which is used to create high performance , pseudo random access data structures where large amount of data is to be stored and accessed quickly. Immutable objects , or objects that can't be altered, are hashable and they have a single unique value that will never change. A hashing function is a function which takes an object, say a string such as "Java" and returns a fixed-size code, assume the return value is an integer .










net-informations.com (C) 2019    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.