Ankush Verma
Ankush Verma

Reputation: 1

Want to change the range of for loop

I'm not sure how for loops work in Python 3:

l=6
for z in range(l):
    print(z)

Can I change the value of l by setting l=10 from within the loop? Will the value of l will be changed to 10 or will remain 6?

If not, how can I manipulate the range from within the loop?

Upvotes: 0

Views: 68

Answers (1)

Sebastian Wozny
Sebastian Wozny

Reputation: 17506

No you cannot manipulate the range from within the loop.

range(l) will be evaluated once to a list containing numbers from 0 to l-1, when the code execution reaches the line with the for statement:

range(l) => [0, 1, 2, 3, 4, 5]

Then the for loop will assign the values in the list to z in order.

If you need more fine grained control you'd have to use a while loop and keep a counter manually:

l = 6
z = 0
while z < l:
    print(z)
    z = z + 1
    l = 10

This would allow you to check on every iteration for a stopping criterion.

Upvotes: 1

Related Questions