Is it possible to increment a for loop inside of the loop in python 3?
for example:
for i in range(0, len(foo_list)):
if foo_list[i] < bar
i += 4
Where the loop counter i
gets incremented by 4 if the condition holds true, else it will just increment by one (or whatever the step value is for the for loop)?
I know a while loop would be more applicable for an application like this, but it would be good to know if this (or something like this) in a for loop is possible.
Thanks!
You could use a while loop and increment i
based on the condition:
while i < (len(foo_list)):
if foo_list[i] < bar: # if condition is True increment by 4
i += 4
else:
i += 1 # else just increment 1 by one and check next `foo_list[i]`
Using a for loop i
will always return to the next value in the range:
foo_list = [1,2,3,4,5,6]
bar = 6
for i in range(len(foo_list)):
print("range i ",i)
if foo_list[i] < bar:
i += 4
print("if i",i)
('range i ', 0)
('if i', 4)
('range i ', 1)
('if i', 5)
('range i ', 2)
('if i', 6)
('range i ', 3)
('if i', 7)
('range i ', 4)
('if i', 8)
('range i ', 5)
In your example as written i
will be reset at each new iteration of the loop (which may seem a little counterintuitive), as seen here:
foo_list = [1, 2, 3]
for i in range(len(foo_list)):
print('Before increment:', i)
i += 4
print('After increment', i)
>>>
Before increment: 0
After increment 4
Before increment: 1
After increment 5
Before increment: 2
After increment 6
continue
is the standard/safe way to skip to the next single iteration of a loop, but it would be far more awkward to chain continues
together than to just use a while
loop as others suggested.
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