6
>>> k = 8
>>> for i in range(k):
        print i
        k -= 3
        print k

Above the is the code which prints numbers from 0-7 if I use just print i in the for loop.

I want to understand the above code how it is working, and is there any way we can update the value of variable used in range(variable) so it iterates differently.

Also why it always iterates up to the initial k value, why the value doesn't updated.

I know it's a silly question, but all ideas and comments are welcome.

0

4 Answers 4

11

You can't change the range after it's been generated. In Python 2, range(k) will make a list of integers from 0 to k, like this: [0, 1, 2, 3, 4, 5, 6, 7]. Changing k after the list has been made will do nothing.

If you want to change the number to iterate to, you could use a while loop, like this:

k = 8
i = 0
while i < k:
    print i
    k -= 3
    i += 1
Sign up to request clarification or add additional context in comments.

1 Comment

Adding on: In Python 3, range is a sequence itself, it doesn't make a list, but it's still based on the value of k at the time it was constructed, with subsequent modifications to k making no difference to the range object.
5

The expression range(k) is evaluated just once, not on every iteration. You can't set k and expect the range(k) result to change, no. From the for statement documentation:

The expression list is evaluated once; it should yield an iterable object.

You can use a while loop instead:

i = 0
k = 8
while i < k:
    print i
    i += 1
    k -= 3

A while loop does re-evaluate the test each iteration. Referencing the while statement documentation:

This repeatedly tests the expression and, if it is true, executes the first suite

Comments

1

If you do want to change k and affect the loop you need to make sure you are iterating over mutable object. For example:

k = list(range(8))
for i in k:
        print(i)
        k.pop()
        k.pop()
        k.pop()
        print(k)

Or alternatively:

k = list(range(8))
for i in k:
        print(i)
        k[:] = k[:-3]
        print(k)

Both will result with

0
[0, 1, 2, 3, 4]
1
[0, 1]

1 Comment

thanks, I already tried this. This was the first thing after i figured out that we cannot change the value of range function again.
0

you could do it like this ,I think, but I dont know if this is what you want.

def to_infinity():
index = 0
while True:
    yield index
    index += 1

for i in to_infinity():
    print(i)

Comments

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.