So I want to do something like this:
for i in range(5):
print(i);
if(condition==true):
i=i-1;
However, for whatever reason, even though I'm decrementing i, the loop doesn't seem to notice. Is there any way to repeat an iteration?
Accepted Answer The only way to go back to a previous iteration is to use a while loop and make the loop counter the appropriate previous value and then "continue".
Let's discuss certain ways in which this can be done. Method #1 : Using reversed() The simplest way to perform this is to use the reversed function for the for loop and the iteration will start occurring from the rear side than the conventional counting.
The only way to go back to a previous iteration is to use a while loop and make the loop counter the appropriate previous value and then "continue". It is much more common to want to stay on the current iteration until a condition is satisfied.
The reason why i=i-1 in your for loop doesn't make it repeat the iteration is simple. In the for loop, i is assigned the value of the next item in the for loop. Python could care less about what you do with i, as long as it is able to assign the next item to it. Thus, the for loop for i in <your_iterable>:<do whatever> is closer to this:
Backward iteration in Python. PythonServer Side ProgrammingProgramming. Sometimes we need to go through the elements of a list in backward order. To achieve this we need to read the last element first and then the last but one and so on till the element at index 0. Various python programming features can be used to achieve this.
To carry out the iteration this for loop describes, Python does the following: Calls iter() to obtain an iterator for a. Calls next() repeatedly to obtain each item from the iterator in turn. Terminates the loop when next() raises the StopIteration exception.
for
loops in Python always go forward. If you want to be able to move backwards, you must use a different mechanism, such as while
:
i = 0 while i < 5: print(i) if condition: i=i-1 i += 1
Or even better:
i = 0 while i < 5: print(i) if condition: do_something() # don't increment here, so we stay on the same value for i else: # only increment in the case where we're not "moving backwards" i += 1
Python loop using range
are by-design to be different from C/C++/Java for
-loops. For every iteration, the i is set the the next value of range(5)
, no matter what you do to i
in between.
You could use a while-loop instead:
i = 0
while i<5:
print i
if condition:
continue
i+=1
But honestly: I'd step back and think again about your original problem. Probably you'll find a better solution as such loops are always error-prone. There's a reason why Python for
-loops where designed to be different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With