0

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?

  • 1
    [Changing the value of range during iteration in Python](https://stackoverflow.com/q/38672963). Or [Modify range variable in for loop (python)](https://stackoverflow.com/a/36051434) – 001 Dec 09 '21 at 20:53
  • 1
    Why would it? The range object doesn't know that the variable was changed, it can't return a next value that depends on it. – Barmar Dec 09 '21 at 20:54
  • A new value is assigned to `i` by the `for` statement at the start of each iteration. You can monkey with `i` inside the loop, but it'll always get reset to the next value from the iterator. – Samwise Dec 09 '21 at 20:54
  • To get your desired result: `for i in range(0, 15, 5): print(i)` – 001 Dec 09 '21 at 20:54
  • I think the OP wants the first 15 multiples of 5, not the multiples of 5 less than 15. – chepner Dec 09 '21 at 20:56
  • Possibly. `for i in range(15): print(i * 5)` – 001 Dec 09 '21 at 20:59
  • If you thought that each iteration would add 1 to `i`, then shouldn't the result be `0, 6, 12, ...`? `i+=5` adds 5, then `for` would add 1 more to it. – Barmar Dec 09 '21 at 21:08

3 Answers3

0

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(/*how many times you want i to print out*/):
    print(i)
    i += 5
0

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

As the others have said, range emits the number and your assignment doesn't matter.

To get the desired result use something like

for i in range(0, 15, 5):
    print(i)

oittaa
  • 599
  • 3
  • 16