Python TypeError: Unhashable Type: ‘list’

Total
0
Shares

Python throws typeerror: unhashable type list when an integer or float is expected but got list. In other terms, a list can’t be hashed. Only integers or floats can. If you try to hash a list, python will throw typeerror unhashable type list.

Introduction

Internally, hash values are the integer representation of dictionary keys which are used for fast lookup of values. Since dictionary keys can’t be a list so Python will throw error when it finds one.

Code Example

d = {'a': 'Tony', 3: 'Stark', 'c': ['is'], ['d']: 'Ironman'}
print(d)

Traceback (most recent call last):
  File "jdoodle.py", line 1, in <module>
    d = {'a': 'Tony', 3: 'Stark', 'c': ['is'], ['d']: 'Ironman'}
TypeError: unhashable type: 'list'

The above code is throwing “typeerror: unhashable type list”. Can you figure out why? The first 3 entries 'a', 3 and 'c' are perfectly valid. All these keys are hashable and Python has no issues with them. The values of all the keys are valid too.

The fourth key is problematic. We are passing a list as 4th key. ['d'] can’t be hashed and hence Python faces trouble. If we convert it into a string as 'd' then this will work fine.

Another solution is to – convert the list into tuple. Tuples are hashable. So, ['d'] could get valid if we convert it to ('d'). In fact, we can have multiple values in tuple like ('d', 'e', 'f') and it will still work fine.

    Tweet this to help others

How do I fix TypeError Unhashable type list in Python?

There are multiple ways to fix typeerror unhashable type list –

  1. Do not use list as key in dictionary. Use int, float, string etc.
  2. If it is needed to use multiple values as key, then convert the list into tuple.

What does unhashable mean in Python?

Unhashable mean which cannot be converted into hashes. Immutable datatypes can be converted into hashes while mutable cannot. An object is hashable if it’s hash value cannot change during lifetime.

Hashable Datatypes

date, datetime, time, timezone, difflib, enum, Fraction, int, float, string, char

Unhashable Datatypes

List, Sets

What is hash() in Python?

hash() return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

Live Demo

Open Live Demo