How do I create an array of every possible combination of pair values?

Question:

So I have a function that will generate a series of pairs. For this example I am using: [11,1], [9,9], [11,1] and the amount of pairs will be greater than or equal to three.

I am trying to create an array that shows every possible combination of these pairs. When I run:

import numpy as np
np.array(np.meshgrid([11,1], [9,9], [11,1])).T.reshape(-1,3)

It produces a correct output of:

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]])

However, since the input can vary, I’d like to store this pair information as a variable and simply plug it into a function for it to work. And no variable type that I’ve input into the function containing the pairs seems to output the correct information.

Any help with this would be much appreciated!

Asked By: Jay Ghosh

||

Answers:

You could use a star operator to “explode” the elements of a tuple (or a list) to be served as function parameters:

import numpy as np
pairs = ([11,1], [9,9], [11,1])
res = np.array(np.meshgrid(*pairs)).T.reshape(-1,3)
print(res)
Answered By: JohanC

This questions is a blatant duplicate of All combinations of a list of lists.


Let’s keep things simple. There’s no reason to use NumPy, plain Python lists and itertools will suffice. Tuples are meant for immutable, fixed length data, lists are mutable and have a variable length. The currently accepted answer swaps the two uses cases for seemingly no reason, so I was careful to use the appropriate data structures.

import itertools as itt

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

combs = itt.product(*pairs)

print(list(combs))

Output:

[(11, 9, 11), (11, 9, 1), (11, 9, 11), (11, 9, 1), (1, 9, 11), (1, 9, 1), (1, 9, 11), (1, 9, 1)]
Answered By: AMC