Nikolay Nikolay - 8 months ago 27
Python Question

Delete unique elements from a list

I faced some problem with solving the next problem:

We have a list of elements (integers), and we should return a list consisting of only the non-unique elements in this list. Without changing order of the list
I think the best way is to delete or remove all unique element.

Take note that I just start to learn python and would like only the simplest solutions.

Here is my code:

def checkio(data):
for i in data:
if data.count(i) == 1: #if element seen in the list just ones, we delet this el
ind = data.index(i)
del data[ind]
return data


Your function can be made to work by iterating over the list in reverse:

def checkio(data):
    for index in range(len(data) - 1, -1, -1):
        if data.count(data[index]) == 1:
            del data[index]
    return data

print(checkio([3, 3, 5, 8, 1, 4, 5, 2, 4, 4, 3, 0]))
[3, 3, 5, 4, 5, 4, 4, 3]
print(checkio([1, 2, 3, 4]))

This works, because it only deletes numbers in the section of the list that has already been iterated over.