mult-indexed xrange?

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Fri Mar 1 15:55:37 EST 2002


The generator facility in 2.2 allows me to do something cool that I always
wanted: looping around multiple indices with just one for-statement, as the
following code does.  Is this available with some built-in functions?
Should we suggest that the definition of range and xrange be thus extended?

Huaiyu


# code example and output
def multixrange(N):
	t = type(N)
	x = [0]*len(N)
	while 1:
		yield t(x)
		for i in xrange(len(N)-1, -1, -1):
			if x[i] < N[i]-1:
				x[i] += 1
				break
			else:
				x[i] = 0
		else:
			raise StopIteration

if __name__ == '__main__':
	for x in multixrange((2,3,2)):
		print x
	for x in multixrange([2,4]):
		print x

"""
Outputs:
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(0, 2, 0)
(0, 2, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)
(1, 2, 0)
(1, 2, 1)
[0, 0]
[0, 1]
[0, 2]
[0, 3]
[1, 0]
[1, 1]
[1, 2]
[1, 3]
"""



More information about the Python-list mailing list