Changing the value of a for loop index on the fly

Mitja nun at example.com
Wed Mar 23 17:08:06 EST 2005


On Wed, 23 Mar 2005 23:27:54 +0100, 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?

Messing with the list/index concerned within the loop itself is rarely a  
good idea and can most often be avoided:

lastFound = 0
for i in range(0, len(subject)):
   if subject[i] in preps:
     psubject.append(noun_syn_parser(subject[lastFound:i]))
     lastFound = i   #you probably want i+1 here? your source says i,  
however

#if having the subject list matters, you can finish it all outside the  
loop with
subject[0:lastFound] = []


HTH
Mitja



More information about the Python-list mailing list