Python: Generating all n-length arrays combinations of values within a range Python: Generating all n-length arrays combinations of values within a range arrays arrays

Python: Generating all n-length arrays combinations of values within a range


You can use itertools.product which is just a convenience function for nested iterations. It also has a repeat-argument if you want to repeat the same iterable multiple times:

>>> from itertools import product>>> amin = 0>>> amax = 2>>> list(product(range(amin, amax), repeat=3))[(0, 0, 0), (0, 0, 1), (0, 1, 0),  (0, 1, 1),  (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

To get the list of list you could use map:

>>> list(map(list, product(range(amin, amax), repeat=3)))[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

However product is an iterator so it's really efficient if you just iterate over it instead of casting it to a list. At least if that's possible in your program. For example:

>>> for prod in product(range(amin, amax), repeat=3):...     print(prod)  # one example(0, 0, 0)(0, 0, 1)(0, 1, 0)(0, 1, 1)(1, 0, 0)(1, 0, 1)(1, 1, 0)(1, 1, 1)


You can use itertools.product:

from itertools import productdef f(mn, mx, n):    return list(product(*[range(mn, mx)]*n)))

Drop list, to return a generator for memory efficiency.


itertools has everything you need. combinations_with_replacement will generate combinations of given length with repeating elements from given iterable. Note that returned value will be iterator.

def f(min, max, num):        return itertools.combinations_with_replacement(range(min, max), num)