I wanted to make a for loop in python with a variable upper bound which is the length of list, the size of which is modified inside the loop.
like this :
l = [1,2,3,4,5,6]
for i in range(len(l)):
del l[i]
I wanted to make a for loop in python with a variable upper bound which is the length of list, the size of which is modified inside the loop.
like this :
l = [1,2,3,4,5,6]
for i in range(len(l)):
del l[i]
l = [1,2,3,4,5,6]
for i in range(len(l)):
del l[0]
Your code makes the list 1 element shorter each iteration. When you reach element 4, your code attempts to delete the fourth element of a list that is only 3 elements long. This results in an out of bounds error.
EDIT To your question if your upper bound is constant: yes it is.
from random import randint
def upper_bound():
print("Generate Range")
return randint(0,9)
for i in range(upper_bound()):
print("Iteration")
pass
That piece of code prints:
Generate Range
Iteration
Iteration
...
Iteration