multiple ranges to for statement?
Terry Reedy
tejarex at yahoo.com
Wed Apr 10 11:03:26 EDT 2002
"Greg Ewing" <greg at cosc.canterbury.ac.nz> wrote in message
news:3CB3DDB9.E0712D39 at cosc.canterbury.ac.nz...
> Ian Bicking wrote:
> > for i in range(a, b) + range(c, d):
> Alternatively:
>
> for seq in range(a, b), range(c, d):
> for i in seq:
> ...
> which avoids building two copies of the sequences.
Nice idiom ("Why didn't I thing of that!"): it scales to k subranges
much better.
To also avoid building all at once (and retyping 'range'), factor
further:
for lo,hi in (a,b),(c,d),(e,f):
for i in range(lo,hi):
...
In 2.2+, one could also write a multirange() generator that would
interprete a string like '1-3,5,8-15,37,88,101-133'. (In 2.1-, use
class instead.)
Terry J. Reedy
More information about the Python-list
mailing list