user225312
user225312

Reputation: 131647

Removing duplicate element from a list and the element itself

I know this question has been asked lots of times, but I am not asking how to remove duplicate elements from a list only, I want to remove the duplicated element as well.

For example, if I have a list:

x = [1, 2, 5, 3, 4, 1, 5]

I want the list to be:

x = [2, 3, 4] # removed 1 and 5 since they were repeated

I can't use a set, since that will include 1 and 5.

Should I use a Counter? Is there a better way?

Upvotes: 2

Views: 377

Answers (4)

Marek Rocki
Marek Rocki

Reputation: 11

How about

duplicates = set(x)
x = [elem for elem in x if elem not in duplicates]

This has the advantage of being O(n) instead of O(n^2).

Edit. Indeed my bad, I must have been half asleep. Mahmoud's answer above is the correct one.

Upvotes: 0

mouad
mouad

Reputation: 70031

Maybe this way:

[_ for _ in x if x.count(_) == 1]

EDIT: This is not the best way in term of time complexity as you can see in the comment above, sorry my mistake.

Upvotes: 3

Mahmoud Abdelkader
Mahmoud Abdelkader

Reputation: 24939

This should be done with a Counter object. It's trivial.

from collections import Counter
x = [k for k, v in Counter([1, 2, 5, 3, 4, 1, 5]).iteritems() if v == 1]
print x

Output:

[2, 3, 4]

Upvotes: 10

Daniel Dinu
Daniel Dinu

Reputation: 1791

Something more verbose and O(n):

x = [1, 2, 2, 3, 4]

def counts_fold(acc, x):
    acc[x] = acc[x]+1 if x in acc else 1
    return acc

counts = reduce(counts_fold, x, {})

y = [i for i in x if counts[i] == 1]

print y

Upvotes: 0

Related Questions