How to filter elements in a list that occur only once

Question:

I need to filter and discard elements in a list that occur only once.

I have the following list of integers as input. I need to make a new list that contains only elements that do not have singular appearances.

item_list = [502, 502, 1341, 1342, 1500, 1500, 2521, 2521, 3078, 3688, 4191, 5185, 5701, 5701]

The desired output list would be like:

item_list = [502, 502, 1500, 1500, 2521, 2521, 5701, 5701]
Asked By: mod13

||

Answers:

You can use collections.Counter:

from collections import Counter

item_list = [502, 502, 1341, 1342, 1500, 1500, 2521, 2521, 3078, 3688, 4191, 5185, 5701, 5701]

c = Counter(item_list)
out = [i for i in item_list if c[i] > 1]
print(out)

Prints:

[502, 502, 1500, 1500, 2521, 2521, 5701, 5701]
Answered By: Andrej Kesely

You can make a new list which checks every value that that doesn’t occur 1, then you set the list to the new list:

item_list = [502, 502, 1341, 1342, 1500, 1500, 2521, 2521, 3078, 3688, 4191, 
5185, 5701, 5701]

new_list = [i for i in item_list if i != 1]

item_list = new_list

print(item_list)
Answered By: Garfird 1231
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.