pythonlistcartesian-productcross-product

cross product in python of arbitrarily many lists


I know you can take the pairwise cross product of lists in the ways posted here: Pairwise crossproduct in Python

but I want to take a list L and a positive integer n and return the cross-product of L with itself n times. Is there a built in way to do this or will I just have to iterate the pairwise cross-product?

(edit: "cartesian product")


Solution

  • You are looking for itertools.product:

    Cartesian product of input iterables.

    Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

    The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order.

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

    So you just need to do

    itertools.product(L, repeat=n)