Python nested looping Idiom Python nested looping Idiom python python

Python nested looping Idiom


You can use itertools.product:

>>> for x,y,z in itertools.product(range(2), range(2), range(3)):...     print x,y,z... 0 0 00 0 10 0 20 1 00 1 10 1 21 0 01 0 11 0 21 1 01 1 11 1 2


If you've got numpy as a dependency already, numpy.ndindex will do the trick ...

>>> for x,y,z in np.ndindex(2,2,2):...     print x,y,z... 0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1


Use itertools.product():

import itertoolsfor x, y, z in itertools.product(range(x_size), range(y_size), range(z_size)):    pass # do something here

From the docs:

Cartesian product of input iterables.

Equivalent to nested for-loops in a generator expression.
...