Why do I get an unhashable type 'list' err

2019-03-04 04:32发布

问题:

Like many other questions on here, I'm attempting to remove duplicates from a list. However, when I execute code that other answers claim work I get the following error:

TypeError: unhashable type: 'list'

on the following line of code:

total_unique_words = list(set(total_words))

Does anyone know a possible solution to this problem? Is this because in most cases the original structure isn't a list?

Thanks!

回答1:

total_words must contain sublists for this error to occur.

Consider:

>>> total_words = ['red', 'red', 'blue']
>>> list(set(total_words))
['blue', 'red']
>>> total_words = ['red', ['red', 'blue']] # contains a sublist
>>> list(set(total_words))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'