How to delete all instances of a repeated number in a list?
You can always have two sets. One to check if seen
and another one to keep unique only. set.discard(el)
will remove if exists.
Inputlist = [2, 3, 6, 6, 8, 9, 12, 12, 14]
seen = set()
ans = set()
for el in Inputlist:
if el not in seen:
seen.add(el)
ans.add(el)
else:
ans.discard(el)
print(list(ans))
EDIT: for giggles I measured the performance of these two solutions
from timeit import timeit
first = """
def get_from_two_sets():
seen = set()
ans = set()
for el in (2, 3, 6, 6, 8, 9, 12, 12, 14):
if el not in seen:
seen.add(el)
ans.add(el)
else:
ans.discard(el)"""
second = """
def get_from_counter():
return [el for el, cnt in Counter((2, 3, 6, 6, 8, 9, 12, 12, 14)).items() if cnt == 1]
"""
print(timeit(stmt=first, number=10000000))
print(timeit(stmt=second, number=10000000, setup="from collections import Counter"))
yields
0.3130729760000577
0.46127468299982866
so yay! it seems like my solution is slightly faster. Don't waste those nanoseconds you saved!
@abc solution is clean and pythonic, go for it.
A simple list comprehension will do the trick:
Inputlist = [2, 3, 6, 6, 8, 9, 12, 12, 14]
Outputlist = [item for item in Inputlist if Inputlist.count(item) == 1]
You can use a Counter
>>> from collections import Counter
>>> l = [2, 3, 6, 6, 8, 9, 12, 12, 14]
>>> res = [el for el, cnt in Counter(l).items() if cnt==1]
>>> res
[2, 3, 8, 9, 14]