Python: shortest way to compute cartesian power of list [duplicate]
Asked Answered
C

1

7

Suppose we have a list L. The cartesian product L x L could be computed like this:

product = [(a,b) for a in L for b in L]

How can the cartesian power L x L x L x ... x L (n times, for a given n) be computed, in a short and efficient way?

Crossfertilize answered 30/1, 2013 at 23:9 Comment(1)
Why is this marked as duplicate. It is not: there is only one list in the OP, whereas the linked question has a list of lists, which is fundamentally different.Crossfertilize
P
11

Using itertools.product():

product = itertools.product(L, repeat=n)

where product is now a iterable; call list(product) if you want to materialize that to a full list:

>>> from itertools import product
>>> list(product(range(3), repeat=2))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Primm answered 30/1, 2013 at 23:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.