multiple discontinued ranges

Mel mwilson at the-wire.com
Wed Nov 10 13:02:48 EST 2010


xoff wrote:

> I was wondering what the best method was in Python programming for 2
> discontinued ranges. e.g. I want to use the range 3 to 7 and 17 to 23.
> Am I obliged to use 2 for loops defining the 2 ranges like this:
> 
> for i in range (3,7):
>  do bla
> for i in range (7,17):
>  do bla
> 
> or is there a more clever way to do this?

One horribly clever way is to concoct a 9-th order polynomial to return 
3,4,5,6,17,18,19,20,21,22 for input values 0,1,2,3,4,5,6,7,8,9.

The reasonable way is to use two loops as you've done.  If the pattern of 
discontinuous ranges is really important in your application, you'd perhaps 
want to package it up (not tested):

def important_range ():
    for x in xrange (3, 7):
        yield x
    for x in xrange (17,23):
        yield x


to be used elsewhere as

for v in important_range():
    # use v ...



	Mel.



More information about the Python-list mailing list