0

I am running a similar for loop but last element is not running , execution is exiting for loop

numbers = [5,6] 
for x in numbers:
   print(x)
   numbers.remove(x)
Sid
  • 2,174
  • 1
  • 13
  • 29
  • Never change the list you are iterating over! – Klaus D. May 04 '21 at 16:38
  • 1
    This answer explains why you cannot modify a list you are looping through: https://stackoverflow.com/questions/1637807/modifying-list-while-iterating#1637875 – Sid May 04 '21 at 16:39

3 Answers3

0

It is usually not best practise to iterate the list you are looping through because things get messy: You could simply remove the remove statement and it will work just fine.

If you want to empty the list you could do so out of the loop like this: numbers = []

If you really need to iterate the list in the for loop though, I suggest you using a copy of your numbers list:

numbers = [5,6]
copied_list = numbers.copy()

for x in numbers:
    print(x)
    copied_list.remove(x)
Thalis
  • 188
  • 2
  • 12
  • *"It is usually not best practise to iterate a list in a loop"* It is actually one of the most important use-cases for a list and completely fine! – Klaus D. May 04 '21 at 16:40
  • @KlausD. Sort of spelling mistake. Thanks for noticing it. Corrected it right away – Thalis May 04 '21 at 16:43
0

If you want to clear this list you could just use clear().

numbers = [5,6] 
numbers.clear()

output

[]

#Note: do not mutate or mess with the iterable you are working with.

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
0

You are not permitted to remove elements from the list while iterating over it using a for loop.

Alternatively, you could use a while loop:

while numbers:
   numbers.pop(0)
   print(numbers)
GonEbal
  • 228
  • 2
  • 8