Defining the argument of a python function to be n of the same lists

Question:

I have a python function itertools.product() and a list A = [1, 2, 3]. I would like to find a way to do itertools.product(A, A, A, ...) where the number of As in the argument can be determined by a variable n.

I tried itertools.product([A]*n), which obviously did not work. I expected this to not work, but I will reiterate that I would like to code something so that itertools.product([A]*n) => itertools.product(A, A, A, ...) where there are n As.

Asked By: Silly Goose

||

Answers:

You can use argument unpacking using *: product(*[A]*n) to stick to your idea, but better use repeat option in that case if all A‘s in your list are to be the same: product(A, repeat=n).

Answered By: Julien

From the documentation:

To compute the product of an iterable with itself, specify the number of repetitions with the optional repeat keyword argument. For example, product(A, repeat=4) means the same as product(A, A, A, A).

Answered By: Selcuk
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.