TypeError: unhashable type: 'list' when using built-in set function
Solution 1:
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)))
Solution 2:
Sets remove duplicate items. In order to do that, the item can't change while in the set. Lists can change after being created, and are termed 'mutable'. You cannot put mutable things in a set.
Lists have an unmutable equivalent, called a 'tuple'. This is how you would write a piece of code that took a list of lists, removed duplicate lists, then sorted it in reverse.
result = sorted(set(map(tuple, my_list)), reverse=True)
Additional note: If a tuple contains a list, the tuple is still considered mutable.
Some examples:
>>> hash( tuple() )
3527539
>>> hash( dict() )
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
hash( dict() )
TypeError: unhashable type: 'dict'
>>> hash( list() )
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
hash( list() )
TypeError: unhashable type: 'list'