title: How can I compute a Cartesian product iteratively?
body: <p><a href="https://stackoverflow.com/questions/2405242/cartesian-product-of-several-vectors">This question</a> asks how to compute the Cartesian product of a given number of vectors. Since the number of vectors is known in advance and rather small, the solution is easily obtained with nested for loops.</p>
  
  <p>Now suppose that you are given, in your language of choice, a vector of vectors (or list of lists, or set of sets, etc.):</p>
  
  <pre><code>l = [ [1,2,3], [4,5], [6,7], [8,9,10], [11,12], [13] ]
  </code></pre>
  
  <p>If I was asked to compute its Cartesian product, that is</p>
  
  <pre><code>[ [1,4,6,8,11,13], [1,4,6,8,12,13], [1,4,6,9,11,13], [1,4,6,9,12,13], ... ]
  </code></pre>
  
  <p>I would proceed with recursion. For example, in quick&amp;dirty python,</p>
  
  <pre><code>def cartesianProduct(aListOfLists):
      if not aListOfLists:
          yield []
      else:
          for item in aListOfLists[0]:
              for product in cartesianProduct(aListOfLists[1:]):
                  yield [item] + product
  </code></pre>
  
  <p>Is there an easy way to compute it <b>iteratively</b>? </p>
  
  <p>(Note: The answer doesn't need to be in python, and anyway I'm aware that in python itertools does the job better, as in <a href="https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists-in-python">this question</a>.)</p>