Remove Unique Elemets From a List

Suppose you have to remove unique elements from a list. This is what you can do:

 

digits = [ 1, 2, 1, 4, 5, 3, 4, 2, 3, 7, 8 ]
copy = []
for x in digits:
    if digits.count(x) == 1:
        copy.append(x)
           
for y in copy:
    digits.remove(y)
print digits


===========================================================

Explanation:

1. Why two loops?

Never remove elements from a list while iterating the same list. This will give unexpected results. Better make a new list, add all the elements to be removed in the new list. Then remove the elements in this new from original list. That's exactly what I have done. 


Comments