-4

When I run the program, the for loop does not delete all the list items, but only certain ones. Why? Here is the code:

def res(array):
   for i in range(len(array)):
      print(array[i])
      del array[i]
      print(array)

arr = [10, 5, 40, 30, 20, 50]
res(arr)
deadshot
  • 8,881
  • 4
  • 20
  • 39
  • The first time through the loop you delete `array[0]`, and all of the other items shift down one position. Then the next time through the loop you delete `array[1]`, and the new `array[0]` remains untouched. – John Gordon May 08 '20 at 16:56
  • Because if you delete the item, then the remaining items shift one to the right, but still you increment `i`, so you move two items forward so to speak. It will normally also raise an `IndexError`. – Willem Van Onsem May 08 '20 at 16:56
  • Do not delete any element while iterating. Will create issues similar to what you are facing. – mad_ May 08 '20 at 16:56
  • use while loop `while arr: print(arr.pop(0))` – deadshot May 08 '20 at 16:57
  • But the general advise is: *never* modify a collection while iterating over it. – Willem Van Onsem May 08 '20 at 16:57

1 Answers1

1

Because you're modifying the list while you're deleting items in it. First you delete the first item, 10. Everything shifts, 5 is now the first item. Then you delete the second item, which is now 40, etc.

Not sure what you want to accomplish, but going through the list in reverse for i in range(len(list)-1,-1,-1) might do it for you.

bastianwur
  • 26
  • 2
  • How iterating in reverse will solve the issue? – mad_ May 08 '20 at 16:58
  • Because this will delete the last item, which will not change the index of any of the other items – bastianwur May 08 '20 at 17:04
  • Why? If I want to delete the elements at first index and middle index then? A general piece of advice does not change the list while iterating over it. – mad_ May 08 '20 at 17:06
  • That is for sure true, that is a different "use case", if you like. And I would also agree with you to not delete while iterating. – bastianwur May 08 '20 at 17:16