covar
covar

Reputation: 21

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]

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

Upvotes: 0

Views: 51

Answers (1)

Aniketh Malyala
Aniketh Malyala

Reputation: 2660

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

Upvotes: 1

Related Questions