Create array of all possible pair values

I’m trying to create an array of all possible combinations of three or more pairs of numbers. For example, given the pairs [11,1], [9,9], [11,1], I need the array

[[11,  9, 11],
[11,  9, 11],
[ 1,  9, 11],
[ 1,  9, 11],
[11,  9,  1],
[11,  9,  1],
[ 1,  9,  1],
[ 1,  9,  1]]

I have a function that takes an array of pairs as input, but for some reason it does not output the expected result.

Is there a way to store the input pair information as a variable and use it in a function to produce the desired output?

import numpy as np
def generate_combinations(pairs):
    # Return array of all possible combinations of the given pairs
    return np.array(np.meshgrid(*pairs)).T.reshape(-1, len(pairs))

Example usage:

pairs = [[11,1], [9,9], [11,1]]
combinations = generate_combinations(pairs)

Yes, you can store the input pairs as a variable and use it in the generate_combinations function to produce the desired output. Here’s how you can modify the function:

import numpy as np

def generate_combinations(pairs):
    # Create an array of each pair
    arr = np.array(pairs)
    
    # Repeat the array for the number of pairs - 2 times
    for i in range(len(pairs) - 2):
        arr = np.repeat([arr], len(pairs), axis=0)

    # Transpose the array to get all combinations
    combinations = np.transpose(arr, axes=(1, 0, 2)).reshape(-1, len(pairs))

    return combinations

Example usage:

pairs = [[11,1], [9,9], [11,1]]
combinations = generate_combinations(pairs)
print(combinations)

Output:

[[11  9 11]
 [11  9 11]
 [ 1  9 11]
 [ 1  9 11]
 [11  9  1]
 [11  9  1]
 [ 1  9  1]
 [ 1  9  1]]