1

I have a list of items below.

a=[['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR08-C2-p20'], ['JR08-C2-p20'], ['JR08-C2-p20'], ['JR08-C2-p20'], ['JR08-C2-p20']]

When I tried to get unique of a as list(set(a)), I get TypeError: unhashable type: 'list'. How do I get the solution for this?

MAPK
  • 5,635
  • 4
  • 37
  • 88

1 Answers1

3

If you don't care about the order, you could convert the data to a hashable type, create a set, and then convert back to lists.

a = [
    ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'],
    ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'],
    ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'],
    ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'], ['JR06-C5-p21'],
    ['JR08-C2-p20'], ['JR08-C2-p20'], ['JR08-C2-p20'], ['JR08-C2-p20'],
    ['JR08-C2-p20']
]

a = list(map(list, set(map(tuple, a))))
print(a)
[['JR08-C2-p20'], ['JR06-C5-p21']]

If insertion order matters, you can do a similar trick as here, with the adaptation that you still transform the inner data to a hashable type:

def filter_unique(seq):
    seen = set()
    return [
        x for x in seq
        if not ((hashable := tuple(x)) in seen or seen.add(hashable))
    ]


print(filter_unique(a))
[['JR06-C5-p21'], ['JR08-C2-p20']]
flakes
  • 21,558
  • 8
  • 41
  • 88
  • `if not ((hashable := tuple(x)) in seen or seen.add(hashable))` just use a for loop – juanpa.arrivillaga Oct 04 '22 at 20:50
  • @juanpa.arrivillaga Yeah, I was just trying not to edit the original code too much where I borrowed that from. Would probably do this with a for loop and have the function be a generator. Then the user can choose what final container type they want explicitly. – flakes Oct 04 '22 at 20:53