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 elements from list if appears more than a specific value in python

Hello i have the following code

list1 = [1,1,1,1]
x = 1
def delete(list1,x):
     for i in list1:
        if list1.count(i) > x:
            list1.remove(i)

expected [1]

output [1,1]

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

Can someone explain why at the last time which count(i) is equal to 2 does not remove element??????

>Solution :

When you are using a for loop to iterate through a list, it is very important that you understand how the iteration changes as you modify the list.

The problem with this code is that once you are removing elements as you iterate, you are skipping elements and thus your loop will end early.

We can fix this problem by simply iterating through a copy of our list, but applying the changes to our original list:

list1 = [1,1,1,1]
x = 1
def delete(list1,x):
     for i in list1.copy(): #change is made here
        if list1.count(i) > x:
            list1.remove(i)

delete(list1,x)
print(list1)

Output:

[1]

I hope this helped! Let me know if you need any further help or clarification 🙂

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