0

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??????

covar
  • 21
  • 4
  • 1
    It is likely because you are modifying the list while iterating over it. – Richard K Yu Feb 22 '22 at 18:09
  • Does this answer your question? [Strange result when removing item from a list while iterating over it](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) – Matthias Feb 22 '22 at 18:11

1 Answers1

1

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

Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14
  • Than you very much. But i have a question. Every time the for statement initializes is the list1 copy of the previous list1 minus the extracted element????? – covar Feb 22 '22 at 18:29