-4

I have a list with several stings, with some being duplicates. I need to pull out all the duplicate strings and append them into a new list. How can I do that?

list_i = ['a','b','a','c','a','c','g','w','s','c','d','a','b','c','a','e']

1 Answers1

0

Use an OrderedDict to get a list without the duplicates then remove those from a copy of the original

from collections import OrderedDict

list_i = ['a','b','a','c','a','c','g','w','s','c','d','a','b','c','a','e']

non_dupes = list(OrderedDict.fromkeys(list_i))

dupes = list(list_i)
for d in non_dupes:
  dupes.remove(d)

print(dupes)
#['a', 'a', 'c', 'c', 'a', 'b', 'c', 'a']
print(non_dupes)
#['a', 'b', 'c', 'g', 'w', 's', 'd', 'e']
Jab
  • 26,853
  • 21
  • 75
  • 114
  • This seems unnecessarily complicated. Why not just `dups = list(filter(lambda x: l.count(x)>1, l))` – Alex V Mar 06 '19 at 21:38
  • Well you are correct, I wasn't trying ot overcomplicate things, although with a counter they have the number of times a letter shows up – Jab Mar 06 '19 at 21:41
  • I edited, the list comprehension is better than a counter all day – Jab Mar 06 '19 at 21:44
  • Using a list comp like you suggested, keeps the duplicates, he wanted them to be removed and keep only the ones that are duplicates. I believe the counter method would have worked but the above is probably the best I can think of. – Jab Mar 06 '19 at 22:05
  • In that case `dups = list(set(filter(lambda x: l.count(x)>1, l)))`. However, he never said he wanted to remove the duplicates in the new list of duplicates (though I agree it's a reasonable assumption). – Alex V Mar 06 '19 at 22:55