-3

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]
Gavriel Cohen
  • 4,355
  • 34
  • 39
  • 5
    Possible duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Ardein_ Mar 19 '19 at 07:57
  • @Dataholic: Any particular reason for not using a `while` loop? A `while` loop offers you the control you are looking for. – fountainhead Mar 19 '19 at 08:01
  • yes it worked with a while loop, i just want to know if the upperbound of a for loop is updated in every iteration or not ? – Dataholic Mar 19 '19 at 08:03
  • If you still want to do it with a for loop, you can use a variation of my answer given here https://stackoverflow.com/questions/54870055/how-to-reset-a-loop-that-iterates-over-a-set/55105308#55105308. That answer gives a technique for re-setting the iterable. You can modify that technique to set a new limit for the iteration. – fountainhead Mar 19 '19 at 08:08
  • The important things to understand in the case of a `for` loop are: **(a)** the evaluation of the expression happens only once. **(b)** The only chance for you to "intercept" or "intervene" is if **you** implement the iterator that is used by the `for` loop, at the start of each iteration. (My answer in that post was to illustrate how a custom iterator can be re-set or re-initialized to start iterating from the beginning again) – fountainhead Mar 19 '19 at 08:17

1 Answers1

0
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
Florian H
  • 3,052
  • 2
  • 14
  • 25
  • is the the upper bound constant, or is it constantly updated ? – Dataholic Mar 19 '19 at 08:00
  • i did update my answer. Next time try to tell us what you want to know, what you tried to achieve your result, what you expected to happen and what happend unexpectedly. Helps against downvotes. – Florian H Mar 19 '19 at 08:57