Skip to main content
6 of 6
added 3 characters in body
xnor
  • 149.7k
  • 26
  • 287
  • 676

Collapse two numerical loops into one

Say you're iterating over the cells of an m*n grid. Instead of two nested for loops, one for the rows and one for the columns, it's usually shorter to write a single loop to iterate over the m*n cells of the grid. You can extract the row and column of the cell inside the loop.

Original code:

for i in range(m): for j in range(n): do_stuff(i,j) 

Golfed code:

for k in range(m*n): do_stuff(k/n,k%n) 

In effect, you're iterating over the Cartesian product of the two ranges, encoding the pair (i,j) as x=i*n+j. You've save a costly range call and a level of indentation inside the loop. The order of iteration is unchanged.

Use // instead of / in Python 3. If you refer to i and j many times, it may be shorter to assign their values i=k/n, j=k%n inside the loop.

xnor
  • 149.7k
  • 26
  • 287
  • 676