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)
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)
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)
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.
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)