You have no control over i when you're using for i in .... It's set to whatever the for loop decides when looping.

Here, just don't use i for your loop index, use an anonymous variable like _ to count 3 times, keep i as a "global" counter:

i=0
while i<10:  # just to stop after a while for the demo
 print("i initialized as", i)
 for _ in range(0,3):
      print ("inside for",i)
      i = i + 1
 print("exit from for i value is",i)

output:

inside for 0
inside for 1
inside for 2
exit from for i value is 3
i initialized as 3
inside for 3
inside for 4
inside for 5
exit from for i value is 6
i initialized as 6
inside for 6
inside for 7
inside for 8
exit from for i value is 9
i initialized as 9
inside for 9
inside for 10
inside for 11
exit from for i value is 12

Aside: while true should be while True. Unlike Java & C++, Booleans are capitalized in python.

Answer from Jean-François Fabre on Stack Overflow
Top answer
1 of 4
13

You have no control over i when you're using for i in .... It's set to whatever the for loop decides when looping.

Here, just don't use i for your loop index, use an anonymous variable like _ to count 3 times, keep i as a "global" counter:

i=0
while i<10:  # just to stop after a while for the demo
 print("i initialized as", i)
 for _ in range(0,3):
      print ("inside for",i)
      i = i + 1
 print("exit from for i value is",i)

output:

inside for 0
inside for 1
inside for 2
exit from for i value is 3
i initialized as 3
inside for 3
inside for 4
inside for 5
exit from for i value is 6
i initialized as 6
inside for 6
inside for 7
inside for 8
exit from for i value is 9
i initialized as 9
inside for 9
inside for 10
inside for 11
exit from for i value is 12

Aside: while true should be while True. Unlike Java & C++, Booleans are capitalized in python.

2 of 4
4

The problem here is that you are trying to modify the loop variable of a for loop. Python doesn't stop you from doing i = i + 1 inside the loop, but as soon as control goes back to the top of the loop i gets reset to whatever value is next in the sequence. That's just the way for loops work in Python, it also happens if you loop over a list or tuple rather than a range. Eg,

for i in (2, 3, 5, 7, 11):
    print(i)
    i = 10 * i
    print(i)

output

2
20
3
30
5
50
7
70
11
110

To get the output you want is easy, though. In the following code I replaced your infinite while loop with a small for loop.

i = 0 
for j in range(3):
    print("\ni initialized as", i)
    for i in range(i, i + 3):
        print ("inside for", i)
    i += 1

output

i initialized as 0
inside for 0
inside for 1
inside for 2

i initialized as 3
inside for 3
inside for 4
inside for 5

i initialized as 6
inside for 6
inside for 7
inside for 8

If the outer loop isn't infinite, you can do this sort of thing with a single loop and an if test. It's more compact, but slightly slower, since it has to perform the test on every loop iteration.

outer_loops = 4
inner_loops = 3
for i in range(outer_loops * inner_loops):
    if i % inner_loops == 0:
        print("\nIteration", i // inner_loops)
    print ("inside for", i)

output

Iteration 0
inside for 0
inside for 1
inside for 2

Iteration 1
inside for 3
inside for 4
inside for 5

Iteration 2
inside for 6
inside for 7
inside for 8

Iteration 3
inside for 9
inside for 10
inside for 11
🌐
Python Morsels
pythonmorsels.com › looping-with-indexes
Looping with indexes - Python Morsels
October 8, 2020 - We start n at 1 and we're incrementing it by 1 in each iteration of our loop. Instead of keeping track of counter ourselves, how about thinking in terms of indices and using range(len(favorite_fruits)) to grab each of the indexes of all the items in this list: >>> favorite_fruits = ["jujube", "pear", "watermelon", "apple", "blueberry"] >>> >>> for i in range(len(favorite_fruits)): ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › how to increment for loop in python
How to Increment For Loop in Python - Spark By {Examples}
May 31, 2024 - Python for loop is usually increment ... 4 e.t.c. You can easily achieve this by using the range() function, with the range you can increment the for loop index with a positive step value....
🌐
Rosetta Code
rosettacode.org › wiki › Loops › Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body - Rosetta Code
2 weeks ago - Although the 1962 Revised Report does not explicitly forbid or permit the practice, the A60 interpreter will allow the index variable (and for that matter, the increment) of a FOR..UNTIL loop to be modified within the loop. However, there is no elegant method of exiting from the loop once the desired number of primes has been found.
🌐
TutorialKart
tutorialkart.com › python › python-for-loop › python-for-loop-increment-step
Python For Loop Increment in Steps
July 22, 2021 - To iterate through an iterable in steps, using for loop, you can use range() function. range() function allows to increment the "loop index" in required amount of steps.
🌐
NI
knowledge.ni.com › KnowledgeArticleDetails
Creating a For Loop with Alternative Starting Index and Increment Value - NI
Home Support Creating a For Loop with Alternative Starting Index and Increment Value
🌐
Enterprise DNA
blog.enterprisedna.co › python-for-loop-index
Python for Loop Index: How to Access It (5 Easy Ways) – Master Data Skills + AI
Inside the loop, i represents the ... and its corresponding color. In this approach, you maintain a separate counter variable, which you initialize before the loop and manually increment within each iteration of the loop....
🌐
GeeksforGeeks
geeksforgeeks.org › ways-to-increment-iterator-from-inside-the-for-loop-in-python
Ways to increment Iterator from inside the For loop in Python - GeeksforGeeks
February 24, 2023 - Example: ... The above example shows this odd behavior of the for loop because the for loop in Python is not a convention C style for loop, i.e., for (i=0; i<n; i++) rather it is a for in loop which is similar to for each loop in other languages.
🌐
Trey Hunner
treyhunner.com › 2016 › 04 › how-to-loop-with-indexes-in-python
How to loop with indexes in Python
We can loop over this range using Python’s for-in loop (really a foreach). This provides us with the index of each item in our colors list, which is the same way that C-style for loops work.
Find elsewhere
🌐
Renan Moura
renanmf.com › início › python for loop increment by 2
Python for loop increment by 2
April 16, 2023 - Finally, I put a step of 2. numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] for i in numbers[1::2]: print(i) ... numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] for i in range(1, len(numbers), 2): print(numbers[i]) ... Again, the same ...
🌐
Reddit
reddit.com › r/learnprogramming › [python] how can you increment a list index using a for / while loop in python?
r/learnprogramming on Reddit: [Python] How can you increment a list index using a for / while loop in Python?
October 30, 2017 -

So I have a particularly nasty API output. It is a list with 20 dictionaries, each dictionary has like 5 others inside of it, and inside some of those there are lists. So I'm breaking down the issue of getting through it.

I'm stuck on how to increment the index of the list so that it goes through all 20 positions of the list. I'm lost. The Java way to do it would be a for loop with i incrementing by i++, and put i into the list index... but I don't think this works?

I have the following code:

i = 0
def next():
    global i # <--- declare `i` as a global variable
    if (i<rankCount): ## want i to run only as many times as there are dictionaries
        # i= i + 1
        for roster_member in response["rankings"][i]["run"]["roster"]: # If it's a tank, print the name
            if roster_member["role"] == "tank":
                print(roster_member["character"]["name"])
            i= i + 1

How can I achieve this incrementing? I tried to declare a function, set a global variable i, then use an if to check if i is less than rankCount which is 20. If i < 20, a for loop, with an if to check the dictionary value. However, it only printed once. It apparently didn't increment and run the loop again :s

🌐
GeeksforGeeks
geeksforgeeks.org › specifying-the-increment-in-for-loops-in-python
Specifying the increment in for-loops in Python - GeeksforGeeks
February 22, 2023 - Example 4: Incrementing the iterator by exponential values of n. We will be using list comprehension. ... Time complexity: O(n), where n is the number of iterations. Auxiliary space: O(1), as only a constant amount of extra space is used to store the value of "i" in each iteration. ... Prerequisite: Python For loops The for loop has a loop variable that controls the iteration.
🌐
Real Python
realpython.com › python-enumerate
Python enumerate(): Simplify Loops That Need Counters – Real Python
June 23, 2025 - Calling enumerate() allows you to control the flow of a loop based on the index of each item in a list, even if the values themselves aren’t important to your logic. You can also combine mathematical operations with conditions for the index. For example, you might need to grab every second item from a Python string.
Top answer
1 of 8
46

There is a fantastic package in Python called itertools.

But before I get into that, it'd serve well to explain how the iteration protocol is implemented in Python. When you want to provide iteration over your container, you specify the __iter__() class method that provides an iterator type. "Understanding Python's 'for' statement" is a nice article covering how the for-in statement actually works in Python and provides a nice overview on how the iterator types work.

Take a look at the following:

>>> sequence = [1, 2, 3, 4, 5]
>>> iterator = sequence.__iter__()
>>> iterator.next()
1
>>> iterator.next()
2
>>> for number in iterator:
    print number 
3
4
5

Now back to itertools. The package contains functions for various iteration purposes. If you ever need to do special sequencing, this is the first place to look into.

At the bottom you can find the Recipes section that contain recipes for creating an extended toolset using the existing itertools as building blocks.

And there's an interesting function that does exactly what you need:

def consume(iterator, n):
    '''Advance the iterator n-steps ahead. If n is none, consume entirely.'''
    collections.deque(itertools.islice(iterator, n), maxlen=0)

Here's a quick, readable, example on how it works (Python 2.5):

>>> import itertools, collections
>>> def consume(iterator, n):
    collections.deque(itertools.islice(iterator, n))
>>> iterator = range(1, 16).__iter__()
>>> for number in iterator:
    if (number == 5):
        # Disregard 6, 7, 8, 9 (5 doesn't get printed just as well)
        consume(iterator, 4)
    else:
        print number

1
2
3
4
10
11
12
13
14
15
2 of 8
17

itertools.islice:

lines = iter(cdata.splitlines())
for line in lines:
    if exp.match(line):
       #increment the position of the iterator by 5
       for _ in itertools.islice(lines, 4):
           pass
       continue # skip 1+4 lines
    print line

For example, if exp, cdata are:

exp = re.compile(r"skip5")
cdata = """
before skip
skip5
1 never see it
2 ditto
3 ..
4 ..
5 after skip
6 
"""

Then the output is:

before skip
5 after skip
6 

Python implementation of the C example

i = 0
while i < 100:
    if i == 50:
       i += 10
    print i
    i += 1

As @[Glenn Maynard] pointed out in the comment if you need to do a very large jumps such as i += 100000000 then you should use explicit while loop instead of just skipping steps in a for loop.

Here's the example that uses explicit while loop instead islice:

lines = cdata.splitlines()
i = 0
while i < len(lines):
    if exp.match(lines[i]):
       #increment the position of the iterator by 5
       i += 5
    else:
       print lines[i]
       i += 1

This example produces the same output as the above islice example.