Python for loop decrementing index
I would like to go over the range() function yet again through the documentation as provided here: Python 3.4.1 Documentation for range(start, stop[, step])
As shown in the documentation above, you may enter three parameters for the range function 'start', 'stop', and 'step', and in the end it will give you an immutable sequence.
The 'start' parameter defines when the counter variable for your case 'i' should begin at. The 'end' parameter is essentially what the size parameter does in your case. And as for what you want, being that you wish to decrease the variable 'i' by 1 every loop, you can have the parameter 'step' be -1 which signifies that on each iteration of the for loop, the variable 'i' will go down by 1.
You can set the 'step' to be -2 or -4 as well, which would make the for loop count 'i' down on every increment 2 down or 4 down respectively.
Example:
for x in range(9, 3, -3):
print(x)
Prints out: 9, 6. It starts at 9, ends at 3, and steps down by a counter of 3. By the time it reaches 3, it will stop and hence why '3' itself is not printed.
EDIT: Just noticed the fact that it appears you may want to decrease the 'i' value in the for loop...? What I would do for that then is simply have a while loop instead where you would have a variable exposed that you can modify at your whim.
test = 0
size = 50
while (test < size)
test += 1
if (some condition):
test -= 1
For such a construct, where you need to vary the loop index, a for
loop might not be the best option.
for <var> in <iterable>
merely runs the loop body with the <var>
taking each value available from the iterable
. Changing the <var>
will have no effect on the ensuing iterations.
However, since it is usually tricky to work out the sequence of values i
will take beforehand, you can use a while
loop.
i = 0
while i < size:
if condition:
...
i -= 1
else:
...
i += 1