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?

7
  • 1
    Changing the value of range during iteration in Python. Or Modify range variable in for loop (python) Commented Dec 9, 2021 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. Commented Dec 9, 2021 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. Commented Dec 9, 2021 at 20:54
  • To get your desired result: for i in range(0, 15, 5): print(i) Commented Dec 9, 2021 at 20:54
  • I think the OP wants the first 15 multiples of 5, not the multiples of 5 less than 15. Commented Dec 9, 2021 at 20:56

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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

3 Comments

This will go past 15.
I know. Thats on purpose because he wants it fifteen times
It's not clear what he wants, or what he's thinking the logic is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.