-1

I need to eliminate duplicates from a list of list like this one:

    list = [[10, 5, 3], [10, 5, 3], [10, 10, 3], [10, 10], [3, 3, 3], [10, 5, 3]]

As a expected result:

    result_list = [[10, 5, 3], [10, 3], [10], [3]]

Eliminating duplicates inside sub-lists and in the main list, would it be possible? I tried with:

    result_list = [list(result) for result in set(set(item) for item in list)]

but throws an TypeError saying that a set is a unhashable type

I think it was not a duplicated question, i need to remove the duplicates within the sublists, not just in the main list. Thanks to everyone who helped me, problem solved.

delete
  • 9
  • 3

4 Answers4

1

Sets aren't hashable, but frozensets are:

lst = [[10, 5, 3], [10, 5, 3], [10, 10, 3], [10, 10], [3, 3, 3], [10, 5, 3]]
result_list = [list(result) for result in set(frozenset(item) for item in lst)]

Also don't shadow the builtin name list, especially if you want to use its usual meaning immediately after.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
0

You should use map in order to convert to tuple

result = [list(set(i)) for i in set(map(tuple, mylist))]

Output

[[3], [10, 3, 5], [10, 3], [10]]
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

You need to use tuples to be able to set, however in a nested list comprehension, you can turn this tuple items back to lists:

list_example = [[10, 5, 3], [10, 5, 3], [10, 10, 3], [10, 10], [3, 3, 3], [10, 5, 3]]
output = [list(x) for x in (list(set([tuple(set(result)) for result in list(set(item) for item in list_example)])))]
print(output)

Output:

[[10, 3, 5], [10], [10, 3], [3]]
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
0

You are iterating a list:

for item in list

putting the results into a set:

set(item)

then putting the set into a set:

set(set(item)

For anything to go into a set it has to be hashable, meaning it has a defined hash value resulting from being an immutable object. sets aren't immutable, and so don't have a hash. See Why aren't Python sets hashable?.

Jon
  • 1,820
  • 2
  • 19
  • 43