Home > other >  Changing the iterator of the for loop inside the code block
Changing the iterator of the for loop inside the code block

Time:12-10

Suppose I have a code block like,

for i in range(15):
    print(i)
    i =5

I expect the i value at each iteration should be i = 0,5,10, ....

Even though I am changing the iterator inside the code block of for loop, the value is not affecting the loop.

Can anyone explain the functionality happening inside?

CodePudding user response:

Here, you're defining i as a number from 0 to 14 everytime it runs the new loop. I think that what you want is this:

i = 0
for _ in range(15):
    print(i)
    i  = 5

CodePudding user response:

A for loop is like an assignment statement. i gets a new value assigned at the top of each iteration, no matter what you might do to i in the body of the loop.

The for loop is equivalent to

r = iter(range(15))
while True:
    try:
        i = next(r)
    except StopIteration:
        break
    print(i)
    i  = 5

Adding 5 to i doesn't have any lasting effect, because i = next(r) will always be executed next.

  • Related