Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get unique of unhashable list in python

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading