[Tutor] Joining multiple lists

Walter Vannini walterv@jps.net
Wed, 23 May 2001 23:20:30 -0700


Here's one way to do it, using reduce.
The idea behind the solution is to find a solution
for two lists. Then, find a way to combine that solution,
with reduce, to get a solution for a variable number of lists.
This is a general technique that can be used in many situations.

def CrossProduct ( PartialProduct, rhs ):
        return [ i+(j,) for i in PartialProduct for j in rhs ]
ListOfLists = [ [1,2,3] , [5,10,15], [20,30,40] ]
Answer = reduce ( CrossProduct, ListOfLists, [()] )
for tup in Answer: print tup

Running the above code will get you:
(1, 5, 20)
(1, 5, 30)
(1, 5, 40)
(1, 10, 20)
(1, 10, 30)
(1, 10, 40)
(1, 15, 20)
(1, 15, 30)
(1, 15, 40)
(2, 5, 20)
(2, 5, 30)
(2, 5, 40)
(2, 10, 20)
(2, 10, 30)
(2, 10, 40)
(2, 15, 20)
(2, 15, 30)
(2, 15, 40)
(3, 5, 20)
(3, 5, 30)
(3, 5, 40)
(3, 10, 20)
(3, 10, 30)
(3, 10, 40)
(3, 15, 20)
(3, 15, 30)
(3, 15, 40)

Walter.

> I'm struggling with a little algorithm and I hope this list can shed
> some light on it.  How would you go about joining a variable number of
> lists together?  I can see two or three but for what I'm doing I can't
> be forced to code for only a couple possibilities.  To clarify what I'm
> doing a little, if you had three lists to join:
> 
> a = 1,2,3
> b = 5,10,15
> c = 20,30,40
> 
> The results would be something like:
> 
> ((1,5,20), (1,5,30), (1,5,40), (1,10,20),
> (1,10,30),(1,10,40),(1,15,20),(1,15,30)....etc).
> 
> Thanks for any advice.
> 
> Joel