title: Best way to iterate through unknown number of lists in general?
body: <p>Given a programming language that supports iteration through lists i.e.</p>
  
  <pre><code>for element in list do
      ...
  </code></pre>
  
  <p>If we have a program that takes a dynamic number of lists as input, <code>list[1] ... list[n]</code> (where <code>n</code> can take any value), what is the best way to iterate through every combination of elements in these lists?</p>
  
  <p>e.g. <code>list[1] = [1,2]</code>, <code>list[2] = [1,3]</code> then we iterate through <code>[[1,1], [1,3], [2,1], [2,3]]</code>.</p>
  
  <p>My ideas that I don't think are very good:</p>
  
  <p>1) Create a big product of these lists into <code>list_product</code> (e.g. in Python you could use <code>itertools.product()</code> multiple times) and then iterate over <code>list_product</code>. Problem is that this requires us to store a (potentially huge) iterable.</p>
  
  <p>2) Find the product of the length of all the lists, total_length and do something along the lines of the following by using a modular arithmetic type idea.</p>
  
  <pre><code>len_lists = [len(list[i]) for i in [1..n]]
  total_length = Product(len_lists)
  for i in [1 ... total_length] do
      total = i-1
      list_index = [1...n]
      for j in [n ... 1] do
          list_index[j] = IntegerPartOf(total / Product([1:j-1]))
          total = RemainderOf(total / Product([1:j-1]))
      od
      print list_index
  od
  </code></pre>
  
  <p>where the <code>list_index</code> are then printed for all different combinations.</p>
  
  <p>Is there a better way with regards to speed (don't care so much about readability)?</p>