Enumerate question: Inner looping like in Perl

Alex Martelli aleaxit at yahoo.com
Sat Oct 30 14:44:08 EDT 2004


Pekka Niiranen <pekka.niiranen at wlanmail.com> wrote:
    ...

> for i, row in enumerate(contents):
>       row[i] = something
>       if matcherSTART.search(row):
>               "Oops! how to advance 'i' and 'row' untill:
>               if matcherEND.search(row):
>                       continue

You take an explicit iterator and call its .next() method (or
equivalently use an inner for on the iterator, if that is sufficient, as
it appears to be in this case -- see later).

> Is there enumerate() hack that I am missing or
> should I go back to idiom?:
> 
> for i in range(len(contents)):
>       if matcherSTART.search(row[i]):
>               while not matcherEND.search(row[i]):
>                       i = i + 1
>                       continue

this 'idiom' won't do what you want; i is set again to the very next
value, ignoring all modifications in the loop's body, when execution
gets back to the loop's header.

Here, probably, is what you want:

looper = iter(enumerate(contents))
for i, row in looper:
    row[i] = something
    if matcherSTART.search(row):
        for i, row in looper:
            if matcherEND.search(row):
                break


Alex



More information about the Python-list mailing list