1

I am generating a matrix of subplots and need to iterate through a list of column and row values such as:

indices = [[1,1], [1,2], [1,3], [2,1], [2,2], [2,3]]

This would be easy to generate with a nested for loop:

rows=2
cols=3
indices = []
for row in range(1, rows + 1):
     for col in range(1, cols + 1):
        indices.append([row, col])

which returns:

<<<indices
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3]]

...but there has to be a cooler way (and, yeah, I know I can turn that into a list comprehension). Any ideas?

jtam
  • 814
  • 1
  • 8
  • 24
  • already answered https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists – Serge Apr 23 '21 at 19:09

1 Answers1

1

You can use itertools.product:

from itertools import product

print(list(product(range(1, 3), range(1, 4))))

Prints:

[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91