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

  • A+
Category:Languages

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.

 


for loops operate on iterables. In for i in range(0, lenDF), i is assigned the next value in the range on each round of the loop regardless of how it is used in the loop. The question then, is whether there is a clean way to write an iterable that does what you want. In this case, all you want is to advance by a fixed step and adjust the final step length to account for the end of data.

endRw=5 lenDF=97   # 1160  for i in range(0, lenDF, endRw):     endIndx = min(i+endRw, lenDF)     print("Range to use: ", i, ":", endIndx) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: