Simple cartesian product

Magnus L. Hetland mlh at vier.idi.ntnu.no
Tue Jan 4 18:06:48 EST 2000


mlh at vier.idi.ntnu.no (Magnus L. Hetland) writes:

> Just wondered if anyone had a simple and elegant little snippet that
> returns the cartesian products of two lists... for-loops and append is
> a simple solution, but not very "cool" ;)
> 
> I have a *nearly* finished function:
> 
> def product(a,b):
>     a = 
>     b = b * len(a)
>     return map(None, a, b)
> 
> What I'm missing here is a simple expression which will make a list
> like [1, 2, 3, 4] into [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] (if
> len(b)==3)...

Hm... A possible solution:

def product(a,b):
    a = reduce(lambda l, x: l + [x]*len(b),
               [[]] + a)
    b = b * len(a)
    return map(None, a, b)

However, this is a bit too obfuscated for my taste...

> 
> (Of course, all of this is a breeze with list comprehension ;)
> 

--

  Magnus
  Lie
  Hetland



More information about the Python-list mailing list