Иван Братчиков Иван Братчиков - 4 months ago 15
Python Question

why 2 and 4 remain in the 2 example?

I need to remove all unique objects in the given lists.

My code passes 1,3,4 checks but doesn't pass 2nd one, it returns [2,4], why not []?

def checkio(data):
for i in data:
if data.count(i) == 1 :
data.remove(i)
return data

if __name__ == "__main__":

assert isinstance(checkio([1]), list), "The result must be a list"
assert checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3], "1st example"
assert checkio([1, 2, 3, 4, 5]) == [], "2nd example"
assert checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5], "3rd example"
assert checkio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9], "4th example"

Answer

The problem here is that you are removing elements from a list while iterating through it, which you should never do.

The iteration for i in data keeps moving the index it's looking at forward. So, when you remove the first element in the list, the next item is moved to index 0 and the loop moves on to look at the element at index 1, skipping over the item that was moved to index 0.

Instead, you can build up a new list containing items that meet your criteria:

items = []
for i in data:
    if (data.count(i) > 1):
        items.append(i)
return items


Or do something like this:

return [i for i in l1 if l1.count(i) > 1]
Comments