In python is there an easier way to write 6 nested for loops? In python is there an easier way to write 6 nested for loops? python python

In python is there an easier way to write 6 nested for loops?


If you're frequently iterating over a Cartesian product like in your example, you might want to investigate Python 2.6's itertools.product -- or write your own if you're in an earlier Python.

from itertools import productfor y, x in product(range(3), repeat=2):  do_something()  for y1, x1 in product(range(3), repeat=2):    do_something_else()


This is fairly common when looping over multidimensional spaces. My solution is:

xy_grid = [(x, y) for x in range(3) for y in range(3)]for x, y in xy_grid:    # do something    for x1, y1 in xy_grid:        # do something else


When faced with that sort of program logic, I would probably break up the sequence of loops into two or more separate functions.

Another technique in Python is to use list comprehensions where possible, instead of a loop.