Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove duplicate entries when it occurs more than twice

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading