Idiom for consecutive loops?
Alex Martelli
aleaxit at yahoo.com
Mon Aug 6 09:43:30 EDT 2001
"Harald Kirsch" <kirschh at lionbioscience.com> wrote in message
news:yv2wv4hqtkw.fsf at lionsp093.lion-ag.de...
"""
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.
Harald Kirsch
P.S.: Please no `while 1:' solutions. I hate them.
"""
No problem, since the closest Python transliteration of your idiom is:
i = 0
while i<lastI:
justDoIt(i)
if someTest(i): break
i += 1
while i<lastI:
doSomethingElse(i)
i += 1
nary a "while 1:" in sight:-).
There are more Pythonic idioms, slightly farther from C but OK; my
personal favorite would be:
for i in range(lastI):
justDoIt(i)
if someTest(i): break
for i in range(i,lastI):
doSomethingElse(i)
You can use xrange instead of range if lastI is a BIG number, but
I'll confess I don't normally bother even thinking about that:-).
Alex
More information about the Python-list
mailing list