ami91 ami91 - 1 year ago 200
Python Question

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

I have a list containing multiple lists as its elements

eg: [[1,2,3,4],[4,5,6,7]]

If I use the built in set function to remove duplicates from this list, I get the error

TypeError: unhashable type: 'list'

The code I'm using is

TopP = sorted(set(TopP),reverse=True)

where TopP is a list just like in the eg. above

Is this usage of set() wrong ? Is there any other way in which I can sort the above list ?


Answer Source

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:
        yield item
        last = item

def sort_and_deduplicate(l):
    return list(uniq(sorted(l, reverse=True)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download