Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!dedekind.zen.co.uk!zen.net.uk!hamilton.zen.co.uk!reader03.nrc01.news.zen.net.uk.POSTED!not-for-mail From: Nobody Subject: Re: looking for a neat solution to a nested loop problem Date: Mon, 06 Aug 2012 17:18:09 +0100 User-Agent: Pan/0.14.2 (This is not a psychotic episode. It's a cleansing moment of clarity.) Message-Id: Newsgroups: comp.lang.python References: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lines: 29 Organization: Zen Internet NNTP-Posting-Host: 6737b8f4.news.zen.co.uk X-Trace: DXC=1DbjK8U5To_E4>eMNjeTQUf2FgniPJjgR=dR0\ckLKGPWeZ<[7LZNRVAd0jRij:Z7UM2Z^cWRFGA[[MNhXjO=kl\ X-Complaints-To: abuse@zen.co.uk Xref: csiph.com comp.lang.python:26634 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? 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().