looking for a neat solution to a nested loop problem

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Aug 7 03:27:07 CEST 2012

On Mon, 06 Aug 2012 19:16:45 +0200, Tom P wrote:

>> def my_generator():
>>      yield 9
>>      yield 100
>>      for i in range(200, 250):
>>          yield i
>>      yield 5
> Thanks, I'll look at that but I think it just moves the clunkiness from
> one place in the code to another.

And if there was a built-in command that did exactly what you wanted, it 
too would also move the clunkiness from one place in the code to another.

What you are asking for is clunky:

    j runs through range(M, 100) and then range(0,M), and 
    i runs through range(N,100) and then range(0,N)
    [end quote]

There's no magic pixie dust that you can sprinkle on it to make it 
elegant. Assuming M and N are small (under 100), you can do this:

values = range(100)  # or list(range(100)) in Python 3.
for j in (values[M:] + values[:M]):
    for i in (values[N:] + values[:N]):

which isn't too bad. If you have to deal with much large ranges, you can 
use itertools to chain them together:

import itertools
jvalues = itertools.chain(xrange(M, 1000000), xrange(M))  # or just range
ivalues = itertools.chain(xrange(N, 2500000), xrange(N))  # in Python 3
for j in jvalues:
    for i in ivalues:


More information about the Python-list mailing list