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 A
s 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
A
s.
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)
.
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)
.
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 A
s 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
A
s.
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)
.
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 asproduct(A, A, A, A)
.