Getting one element from each list, random number of lists

Viewed 62

I want to create a function to take one number from each list and create possible combinations of the numbers. I don't know how many lists will appear every time... For example:

Getting 4 lists: x1, x2, x3 and x4, I need to get output:

(x1[0], x1[0], x1[0], x1[0]), (x1[0], x1[0], x1[0], x1[1]), (x1[0], x1[0], x1[0], x1[2])... or in any other format.

I know how to get it from specific amount of lists using for loop:

for i in range(len(x1)):
    for j in range(len(x2)):
        etc ...

but how may I get it when the number of lists is random?

Thanks

1 Answers

itertools.product does exactly that. It takes a variable number of arguments, so we can use *lists to unpack our list-of-lists into one argument for each list:

>>> import itertools
>>> x1 = ['f', 'g', 't']
>>> x2 = ['a', 'e', 'o']
>>> x3 = ['t', 'd', 'r']
>>> lists = [x1, x2, x3]
>>> list(itertools.product(*lists))
[('f', 'a', 't'), ('f', 'a', 'd'), ('f', 'a', 'r'), ('f', 'e', 't'), ('f', 'e', 'd'), ('f', 'e', 'r'), ('f', 'o', 't'), ('f', 'o', 'd'), ('f', 'o', 'r'), ('g', 'a', 't'), ('g', 'a', 'd'), ('g', 'a', 'r'), ('g', 'e', 't'), ('g', 'e', 'd'), ('g', 'e', 'r'), ('g', 'o', 't'), ('g', 'o', 'd'), ('g', 'o', 'r'), ('t', 'a', 't'), ('t', 'a', 'd'), ('t', 'a', 'r'), ('t', 'e', 't'), ('t', 'e', 'd'), ('t', 'e', 'r'), ('t', 'o', 't'), ('t', 'o', 'd'), ('t', 'o', 'r')]
Related