Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.mixmin.net!news.musoftware.de!wum.musoftware.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Tom P Newsgroups: comp.lang.python Subject: Re: looking for a neat solution to a nested loop problem Date: Mon, 06 Aug 2012 19:14:57 +0200 Lines: 39 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net Dms9LjUjF8+On7ZF9KmPVQ/2jqtOxAr4zPE5E05jWRHFz4SsJonY/7tIplCct7t/0= Cancel-Lock: sha1:sPtSINYqtQgBQ1/5ATYywg4iOUQ= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:14.0) Gecko/20120714 Thunderbird/14.0 In-Reply-To: Xref: csiph.com comp.lang.python:26640 On 08/06/2012 06:18 PM, Nobody wrote: > On Mon, 06 Aug 2012 17:52:31 +0200, Tom P wrote: > >> consider a nested loop algorithm - >> >> for i in range(100): >> for j in range(100): >> do_something(i,j) >> >> Now, suppose I don't want to use i = 0 and j = 0 as initial values, but >> some other values i = N and j = M, and I want to iterate through all >> 10,000 values in sequence - is there a neat python-like way to this? > > for i in range(N,N+100): > for j in range(M,M+100): > do_something(i,j) > > Or did you mean something else? no, I meant something else .. j runs through range(M, 100) and then range(0,M), and i runs through range(N,100) and then range(0,N) .. apologies if I didn't make that clear enough. > > Alternatively: > > import itertools > > for i, j in itertools.product(range(N,N+100),range(M,M+100)): > do_something(i,j) > > This can be preferable to deeply-nested loops. > > Also: in 2.x, use xrange() in preference to range(). >