Nested For Loops

last modified: February 17, 2008

NestedForLoops is a pattern used to walk over a grid or a table.

for X in ROWS:
  for Y in COLUMNS:
    do-something( X, Y )

Whenever you face a table or a grid, and you want to consider each item in it, put a for loop inside of a for loop.

See also CartesianProduct


This is something extremely trivial to all programmers. It is comparable to striking a nail into wood, for a carpenter. Why am I making this page then? To demonstrate what I believe are BlockDesignPatterns. Or, "DesignPatterns" for code blocks. -- LionKimbro


The ListComprehension syntax in PythonLanguage allows nested loops in one line:

results = [do_something(x, y) for x in these for y in those]

Python's generators and tuple unpacking allow the nesting to be flattened:

locations = ((x, y) for x in rows for y in columns)
for (x, y) in locations:
    do_something(x, y)

or (implementing GameOfLife)

neighbors = ((x + dx, y + dy) for dx in (-1, 0, 1) for dy in range(-1, 0, 1) if dx != 0 or dy != 0)
alive = sum(cells[location] for location in neighbors) in (3, 4)

Wouldn't this be much more efficiently done in JayLanguage, or similar, particularly with increases in parallelism such as afforded by the CellProcessor?


Loading...