3

I have found a lot of threads on removing duplicates in arrays but none for my specific use-case. I have a two-dimensional list that I need to remove duplicates from however I must maintain the original sequence

mylist = [['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]

I need to simply drop the duplicates without re-arranging, so..

newlist = [['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]

appreciate any help

3 Answers 3

8

Using set to keep track of seen items:

>>> mylist = [['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]
>>> seen = set()
>>> newlist = []
>>> for item in mylist:
...     t = tuple(item)
...     if t not in seen:
...         newlist.append(item)
...         seen.add(t)
...
>>> newlist
[['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]

NOTE

You need to convert a list to tuple (list is not hashable); can't add a list to set.

>>> seen = set()
>>> seen.add([1,2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> seen.add(tuple([1,2]))
>>>
Sign up to request clarification or add additional context in comments.

Comments

5
mylist = [['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]
result = []
for x in mylist:
    if x not in result:
        result.append(x)
print result

[['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]

1 Comment

Loved this. Is there a way to remove the item from the list, if the list is mutable? Instead of creating a new one.
4

import numpy as np :

myList = [['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]

mylist=np.unique(myList,axis=0)

print (mylist)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.