1

I have simple list and I want to remove all elements one by one. Here is the simplified version:

lst=[2,5]
for i in lst:
    print(i)
    lst.remove(i)

It only remove 2 but element 5 remain. I know the reason as it has been answered in cannot remove the last element of a python list and in Python remove element in list. I also know it might be a bad practice. However both Q/A did not offer the alternative solution what is the good practice to solve this problem. Any help?

Hajar
  • 93
  • 1
  • 6
  • Use `lst.clear()`. If you need Python 2 support as well, use `del lst[:]`. – wim Nov 13 '20 at 01:14
  • 1
    The solution I do is to create another list to accumulate what I want to remove and then remove them outside the loop. lst=[2,5] lst2=[] for i in lst: print(i) lst2.append(i) for j in lst2: lst.remove(j) – Kardi Teknomo Nov 13 '20 at 01:27
  • Thank you this is the solution that I was looking for – Hajar Nov 13 '20 at 01:29

0 Answers0