Home > Software engineering >  Remove elements from list if appears more than a specific value in python
Remove elements from list if appears more than a specific value in python

Time:02-23

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]

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

CodePudding user response:

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 :)

  • Related