I have a list which contains the below values.
list1= ['AAB', 'CAA', 'ADA']
How should I remove duplicates in each item in a list such that i get the following output
list1= ['AB', 'CA', 'AD']
The order should be preserved here
I have a list which contains the below values.
list1= ['AAB', 'CAA', 'ADA']
How should I remove duplicates in each item in a list such that i get the following output
list1= ['AB', 'CA', 'AD']
The order should be preserved here
You can use set
combined with list comprehension if you don't want the letter ordering to be preserved:
list1= ['AAB', 'CAA', 'ADA']
list1 = [''.join(set(l)) for l in list1]
print(list1)
Or use OrderedDict
if you want the ordering to be preserved:
from collections import OrderedDict
list1= ['AAB', 'CAA', 'ADA']
list1 = [''.join(OrderedDict.fromkeys(l).keys()) for l in list1]
print(list1)
You can create a dict using characters on the strings as keys to eliminate duplicates.
list1= ['AAB', 'CAA', 'ADA']
list1 = [''.join(dict.fromkeys(l).keys()) for l in list1]
print(list1)
Loop over the list, cast to set, join
new_list = []
for word in list1:
new_list.append(''.join(set(word)))
A regex solution for fun:
>>> import re
>>> [re.sub(r'(.)(?=.*\1)', '', s[::-1])[::-1] for s in list1]
['AB', 'CA', 'AD']
You can omit the reversals if you're ok with keeping the last occurrence of each:
>>> [re.sub(r'(.)(?=.*\1)', '', s) for s in list1]
['AB', 'CA', 'DA']
Proper solution would be:
>>> [''.join(dict.fromkeys(s)) for s in list1]
['AB', 'CA', 'AD']
(Not sure why the others use .keys()
, that just unnecessarily costs extra code, time and space.)