How to remove all duplicates in python list other than keywords in a separate list?

35 views Asked by At

I'm trying to remove all duplicates from a python list, other than keywords that are stored in another list.

For example:

a = ['a','a','b','b','c','c']
keywords = ['a','b']
some_func(a,keywords) = ['a','a','b','b','c']

How could I do this in the most pythonic way possible?

1

There are 1 answers

0
Rakesh On

This is one approach using a simple iteration.

a = ['a','a','b','b','c','c']
keywords = ['a','b']

def removeDup(a, keywords):
    res = []
    for i in set(a):
        if i in keywords:
            res.extend([i]*a.count(i))
        else:
            res.append(i)
    return res
print(removeDup(a, keywords))

Output:

['a', 'a', 'c', 'b', 'b']
  • Note: This might break the order of the output.