0

The problem is to use "remove" method to empty the list. not understanding why the loop is not deleting all elements in the list. logically, this should work but it's not working. Please identify the problem and suggest a fix or different method.

thislist = ["apple", "banana", "cherry"]
for x in thislist:
    thislist.remove(x)
print(thislist)

I was trying to remove every item via remove method, yes I know that I can also use the "clear" method but the question is to use remove method. Logically this should work but it's not. please explain this.

Vedang
  • 1
  • 1
  • 1
    Never change a list you are iterating over. – Klaus D. Feb 10 '23 at 04:30
  • Using for loop with remove can cause unexpected results. Maybe use a `while` loop? – ThisaruG Feb 10 '23 at 04:32
  • when you are applying for loop the list size changes at every iteration to resolve you can copy the list.! like `for x in thislist.copy():` – Yash Mehta Feb 10 '23 at 04:34
  • @YashMehta Your method also worked, btw I used the 0th element of the list, which always there until there is nothing in the list, then how? – Vedang Feb 10 '23 at 09:00

0 Answers0