Increasing the for loop, inside the loop

Is it possible to increase a for loop inside a loop in python 3?

eg:

for i in range(0, len(foo_list)):
    if foo_list[i] < bar
        i += 4

      

Should the loop counter i

increment by 4 if the condition is true, otherwise it will just increment by one (or any step value for a for loop)?

I know a while loop would be more applicable for such an application, but it would be helpful to know if this (or something similar) is possible in a for loop.

Thank!

+3


source to share


4 answers


You can use while loop and increment i

based on 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)

      

+7


source


Your example, as written, i

will be reset on each new iteration of the loop (which may seem a bit contradictory) as shown 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 go to the next single iteration of the loop, but it would be much more difficult to combine continues

together and not just use a loop while

as others have suggested.

+1


source


a bit hackish ...

>>> b = iter(range(10))
>>> for i in b:
...     print(i)
...     if i==5 : i = next(b)
... 
0
1
2
3
4
5
7
8
9
>>> 

      

+1


source


while i < end:
  # do stuff
  # maybe i +=1
  # or maybe i += 4

      

I suppose you could do it in a for loop if you tried, but that is not practical. The whole point of a python for loop is to look at elements, not indices

0


source







All Articles