Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loops in Python - how to modify i inside the loop

This code was written in Python 3.6 in Jupyter Notebooks. In other languages, I am pretty sure I built loops that looked like this:

endRw=5
lenDF=100   # 1160

for i in range(0, lenDF):
    print("i: ", i)
    endIndx = i + endRw
    if endIndx > lenDF:
                endIndx = lenDF

    print("Range to use: ", i, ":", endIndx)
    # this line is a mockup for an index that is built and used
    # in the real code to do something to a pandas DF

    i = endIndx
    print("i at end of loop", i)

In testing though, i does not get reset to endIndx and so the loop does not build the intended index values.

I was able to solve this problem and get what I was looking for by building a while loop like this:

endRw=5
lenDF=97   # 1160
i = 0
while i < lenDF:
    print("i: ", i)
    endIndx = i + endRw
    if endIndx > lenDF:
                endIndx = lenDF

    print("Range to use: ", i, ":", endIndx)
    # this line is a mockup for an index that is built and used
    # in the real code to do something to a pandas DF

    i = endIndx
    print("i at end of loop: ", i)

Question: is there a way to modify the i from inside the for loop in python? Is there a way to do what I did with the while loop using a for loop in Python?

Solved the problem with while but just curious about this.

like image 241
TMWP Avatar asked Jun 03 '18 21:06

TMWP


1 Answers

You can modify the loop variable in a for loop, the problem is that for loops in Python are not like "old-style" for loops in e.g. Java, but more like "new-style" for-each loops.

In Python, for i in range(0, 10): does not behave like for (int i = 0; i < 10; i++) {, but like for (int i : new int[] {0, 1, ..., 10}}.

That is, in each iteration of the loop, the loop head will not modify the loop variable (e.g. increment it), but assign a new value to it, i.e. the next value from the given iterable (a range in your case). Thus, any modification that you did in the previous iteration are overwritten.

If you want to loop a known number of iterations or for every item in an iterable, use a for loop, but if you want to loop until a certain condition (no longer) holds, as in your case, use while.

like image 143
tobias_k Avatar answered Oct 04 '22 02:10

tobias_k