So I wrote a for loop like this:
for i in range(size):
if(.....)
....
i-=1
else:
....
I try to decrease the index by 1 if it is inside the if
statement, but apparently I can't do that. Is there any other way that I can decrease i
in a for loop?
We can get this position by subtracting 1 from the length of the list. We then loop over our list while the value of our integer is greater than or equal to 0. After each iteration, we decrement the value of our integer by 1, using the augmented assignment operator.
You have to set your range() function correctly. In order to decrement the loop you can use while loop or you can change your algorithm and set the for loop but now what you can do is if you can select the range functions step value to -1.
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
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