0

Suppose, I have a list below

list = [1,1,1,1,2,3,1,4,4,4,4,3,3]

I want to remove the duplicates which occur more than twice. Basically, I want like this

[1,1,2,3,4,4,3,3]

I use the following code

i = 0
while i < len(list) -2:
    if list[i] == list[i+2]:
        del list[i+2]
    else:
        i = i+2

this code gives me the following output

[1, 1, 2, 3, 1, 4, 4, 4, 3, 3]

Here 4 occurs thrice, but I want twice. How can I modify the code or any other method that could give the desired output?

1 Answers1

1
i = 2
while i < len(list):
    if list[i] == list[i-1] and list[i] == list[i-2]:
        del list[i]
    else:
        i += 1
print(list)

output :

[1, 1, 2, 3, 1, 4, 4, 3, 3]
patate1684
  • 639
  • 3
  • 17
  • Thank you, but the problem is that if the 1 repeats again, it removes from the first entry. Say list = [1,1,1,1,2,3,1,4,4,4,4,3,3,1,1]. Applying your solution gives me [2, 3, 1, 4, 4, 3, 3, 1, 1]. But the output should be [1,1, 2, 3, 1, 4, 4, 3, 3, 1, 1] – Bloodstone Programmer Dec 10 '21 at 20:53
  • I have updated my answer. Just put i=2 at the begenning – patate1684 Dec 10 '21 at 20:55