0
list1=[1,2,3,4,5]
for i in list1:
    list1.remove(i)
print(list1)

why the output is [2,4] why not empty list as the value of I will be list elements

ewokx
  • 2,204
  • 3
  • 14
  • 27
Chirag
  • 1
  • Don't add/remove items from a list as you're iterating over it. Confusing things happen. – John Gordon Jul 14 '22 at 04:17
  • Thing is you are doing modification operation on iteration so that list is getting updated on each iteration. for your case, when you removing first element in the list1 in for loop, the 2 becomes first element after that, so 2nd iteration looks for second element which is now 3, because of this 2,4 are left out, instead use `list1.pop()` inside the loop to make list empty for your case. hope this helps. thanks. – y051 Jul 14 '22 at 06:32

0 Answers0