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 e.g. Above
Is this usage of set() wrong? Is there any other way in which I can sort the above list?
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:
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:
Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.