0

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"

2 Answers2

2

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]
xgord
  • 4,606
  • 6
  • 30
  • 51
0

The 'remove' function automatically recreates the list. So when "1" was removed, "2" was put in that slot, so it won't check that same position again, which is why alternating items are remaining. However, you can still implement the same function as you have, but instead work from the back of the list and iterate to the front:

def checkio(data):
     for i in range(len(data)-1,-1,-1):
         if data.count(data[i]) == 1 :
             data.remove(data[i])
     return data
Mukherjee
  • 486
  • 1
  • 3
  • 11