Changing the value of a for loop index on the fly

Tim Roberts timr at probo.com
Thu Mar 24 02:25:38 EST 2005


"Gabriel F. Alcober" <gfa1977 at yahoo.ca> wrote:
>
>Hi! There goes a newbie trouble:
>
>for i in range(0, len(subject)):
>        if subject[i] in preps:
>            psubject.append(noun_syn_parser(subject[0:i]))
>            subject[0:i] = []
>
>Since the last line eliminates some elements of the list, I'm wondering 
>if it's somehow possible to change the value of "i" to 0 in order not to 
>get an index error. Any other ideas?

You got a lot of good responses to this, but it is a fault of mine that I
always want people to understand WHY their proposals won't work.

You CAN, in fact, change "i" within the loop, and your changed value will
survive until the next iteration.  So, this prints 5 copies of 17:

    for i in range(5):
        i = 17
        print i

However, a "for" loop in Python is quite different from a "for" loop in C
or Basic.  In those languages, the end of a loop is determined by some
Boolean comparison, so changing the index alters the comparison.

In the case of Python, the "for" statement just iterates through a set of
values.  "range(5)" is just a normal function that creates the list
[0,1,2,3,4].  The "for" statement keeps running the loop until it runs out
of values in that list or tuple.

So, you CAN change the value of i, but it won't change the operation of the
loop.
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list