Removing Duplicates from a List While Preserving Unique Elements

Hi everyone,

I have a list in Python: [1, 2, 3, 4, 5, 1, 6, 7, 8, 9, 1, 4, 7].

I need to create two separate lists from this:

  1. [2, 3, 5, 6, 8, 9] which contains elements that appear only once in the original list.
  2. [1, 4, 7] which contains elements that appear multiple times in the original list.

Could anyone help me with a way to remove the duplicates from the original list while preserving these unique and duplicate elements in their respective lists?

Thanks in advance!

I don’t think that it’s the optimal solution, but you can try it.

2 Likes

Or this.

2 Likes

With python…

from collections import Counter

lst = [1, 2, 3, 4, 5, 1, 6, 7, 8, 9, 1, 4, 7]
counts = Counter(lst)
singles = [k for k, v in counts.items() if v == 1]
multiples = [k for k, v in counts.items() if v > 1]

another_way = list(filter(lambda k: counts[k] == 1, counts))

EDIT Without list comprehensions

multiples = list(Counter(lst) - Counter(set(lst)))
singles = list(set(lst).difference(multiples))
3 Likes

hi

lst=IN[0]
lst_u=[]
for i in lst:
    if lst.count(i)==1:
        lst_u.append(i)

OUT = lst_u

cordially
christian.stan

2 Likes

hi,

3 Likes