[Tutor] Joining multiple lists

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 23 May 2001 22:24:50 -0700 (PDT)


On Wed, 23 May 2001, JRicker wrote:

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

It will be helpful to try doing it with two lists first.  If we can do it
with two lists, then doing it with multiple lists shouldn't be bad.

Let's pretend that we do have something that gives all possible pairs from
two lists, and call this hypothetical function "allPossiblePairs()".  
Since we're in a fantasy, let's also pretend that we know how it will
work:

###
>>> x = allPossiblePairs([1, 2, 3], [5, 10, 15])
>>> x
[(1, 5), (1, 10), (1, 15),
 (2, 5), (2, 10), (2, 15),
 (3, 5), (3, 10), (3, 15)]
###

There's a reason reason why doing it with two lists is useful: what
happens when we try doing something like this?

###
>>> a = 1, 2, 3
>>> b = 5, 10, 15
>>> c = 20, 30, 40
>>> list1 = allPossiblePairs(b, c)
>>> list2 = allPossiblePairs(a, list1)
###

What comes out won't exactly look like what we want with three lists, but
it will be very close: there will be some extra parentheses in there.  
For example, list2 will probably contain these sort of elements:

    [(1, (5, 20)),  (1, (5, 30)),  ...]

and you can probably do something to fix it.

If we add an additional list 'd' and try to take all possible combinations
of four lists, let's see what that code might look like:

###
>>> d = 100, 200, 300
>>> list3 = allPossiblePairs(d, list2)
###

Again, we'll have too many parentheses in each element, but it's darn
close to what you'll want.  To fix those extra parens, I think that Alan
Gauld's tutorial mentions a way of "flattening" anything that looks like:

    (1, (2, (3, 4))) ===>flattening===>  (1, 2, 3, 4)

but I can't find the page.

This should give you an idea about how to make your program work for lists
of any length.  Good luck!