Idiom for consecutive loops?

Thomas Bellman bellman at lysator.liu.se
Mon Aug 6 18:14:08 EDT 2001


Harald Kirsch <kirschh at lionbioscience.com> wrote:

> When programming in C I find myself writing consecutive loops like

>   for(i=0; i<lastI; i++) {
>     justDoIt(i);
>     if( someTest(i) ) break;
>   }
>   /* the next loop continues were the last one stopped */
>   for(/**/; i<lastI; i++) {
>     doSomethingElse(i);
>   }

> The nice thing is that this is safe even if someTest never becomes
> true in the first loop.

> How would I do that in python, in particular when looping over list
> elements rather than just over numbers.

When looping over a list, how about this:

    lit = iter(haralds_list)
    for item in lit:
	justDoIt(lit)
	if someTest(lit):
	    break
    for item in lit:
	doSomethingElse(lit)

It doesn't work if you are using some stone-age version of
Python, like the two and a half week old 2.1.1.  You've got
to use something modern, like 2.2a1 (which seems to actually
be a couple of days *older* than 2.1.1...).


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Beware of bugs in the above code; I have    !  bellman @ lysator.liu.se
 only proved it correct, not tried it."      !  Make Love -- Nicht Wahr!



More information about the Python-list mailing list