The Python Oracle

Incrementing a for loop, inside the loop

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Secret Catacombs

--

Chapters
00:00 Question
00:45 Accepted answer (Score 11)
01:26 Answer 2 (Score 1)
01:40 Answer 3 (Score 1)
02:20 Answer 4 (Score 0)
03:01 Thank you

--

Full question
https://stackoverflow.com/questions/2641...

Answer 3 links:
[send]: https://docs.python.org/3/reference/expr...
https://repl.it/@blhsing/ImpossibleAcrob...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #loops #forloop #increment

#avk47



ACCEPTED ANSWER

Score 12


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)



ANSWER 2

Score 2


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
>>> 



ANSWER 3

Score 1


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.




ANSWER 4

Score 0


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

I suppose you could do this in a for loop if you tried, but it's not advisable. The whole point of python's for loop is to look at items, not indices