Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'For' loop behaviour in Python

Why is the following simple loop not saving the value of i at the end of the loop?

for i in range( 1, 10 ):
    print i
    i = i + 3

The above prints:

1
2
3
4
5
6
7
8
9

But it should print:

1
4
7
like image 427
Nishant Singh Avatar asked Mar 03 '16 09:03

Nishant Singh


1 Answers

for sets i each iteration, to the next value from the object being iterated over. Whatever you set i to in the loop is ignored at that point.

From the for statement documentation:

The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed.

i is the target list here, so it is assigned each value from the range(1, 10) object. Setting i to something else later on doesn't change what the range(1, 10) expression produced.

If you want to produce a loop where you alter i, use a while loop instead; it re-tests the condition each time through:

i = 1
while i < 10:
    print i
    i += 3

but it'll be easier to just use a range() with a step, producing the values up front:

for i in range(1, 10, 3):
    print i
like image 175
Martijn Pieters Avatar answered Sep 30 '22 16:09

Martijn Pieters