Typeerror: Unhashable Type: 'List' When Using Built-In Set Function

TypeError: unhashable type: 'list' when using built-in set function

Sets require their items to be hashable. Out of types predefined by Python only the immutable ones, such as strings, numbers, and tuples, are hashable. Mutable types, such as lists and dicts, are not hashable because a change of their contents would change the hash and break the lookup code.

Since you're sorting the list anyway, just place the duplicate removal after the list is already sorted. This is easy to implement, doesn't increase algorithmic complexity of the operation, and doesn't require changing sublists to tuples:

def uniq(lst):
last = object()
for item in lst:
if item == last:
continue
yield item
last = item

def sort_and_deduplicate(l):
return list(uniq(sorted(l, reverse=True)))

In python, why do I get an error message of unhashable type:'list' when doing list(set(listB)-set(listA))?

sets require to hash the objects, and lists are not hashable (as they are mutable).

Thus you need to convert to tuple and back to list:

listA=[[0,1,2]]
listB=[[0,1,2],[0,1,3],[0,2,3]]
listC=list(map(list,set(map(tuple,listB))-set(map(tuple,listA))))
listC

output: [[0, 1, 3], [0, 2, 3]]

unhashable type: 'list' while in function, but works well outside the function

A list cannot be used as a key in a dictionary because it is unhashable. You can use a tuple instead.

How to overcome TypeError: unhashable type: 'list'

As indicated by the other answers, the error is to due to k = list[0:j], where your key is converted to a list. One thing you could try is reworking your code to take advantage of the split function:

# Using with ensures that the file is properly closed when you're done
with open('filename.txt', 'rb') as f:
d = {}
# Here we use readlines() to split the file into a list where each element is a line
for line in f.readlines():
# Now we split the file on `x`, since the part before the x will be
# the key and the part after the value
line = line.split('x')
# Take the line parts and strip out the spaces, assigning them to the variables
# Once you get a bit more comfortable, this works as well:
# key, value = [x.strip() for x in line]
key = line[0].strip()
value = line[1].strip()
# Now we check if the dictionary contains the key; if so, append the new value,
# and if not, make a new list that contains the current value
# (For future reference, this is a great place for a defaultdict :)
if key in d:
d[key].append(value)
else:
d[key] = [value]

print d
# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

Note that if you are using Python 3.x, you'll have to make a minor adjustment to get it work properly. If you open the file with rb, you'll need to use line = line.split(b'x') (which makes sure you are splitting the byte with the proper type of string). You can also open the file using with open('filename.txt', 'rU') as f: (or even with open('filename.txt', 'r') as f:) and it should work fine.

Type Error: unhashable type: list when using Python set of strings

words is a list of lists since word_tokenize() returns a list of words.

When you do [word for word in words if word not in custom_stopwords] each word is actually of a list type. When the word not in custom_stopwords "is in set" condition needs to be checked, word needs to be hashed which fails because lists are mutable containers and are not hashable in Python.

These posts might help to understand what is "hashable" and why mutable containers are not:

  • In Python, why is a tuple hashable but not a list?
  • What do you mean by hashable in Python?
  • Hashable, immutable

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

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 (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

Python list operation error : unhashable type 'list'

A set requires its members to be hashable as well. You should use a list of tuples instead of a list of lists:

A = [('a', 10), ('b', 50), ('d', 20), ('b', 50)]

A set is basically a dictionary without values for the keys.



Related Topics



Leave a reply



Submit