How do I iterate over the product of different lists?
<p>I have the following problem:</p>

<p>I have a list <code>l1</code> and I want to iterate over the product with the function <code>itertools.product</code>, I also want to include the second list <code>l2</code> in the same way.</p>

<p>For example:</p>

<pre><code>l1 = [1, 2, 3, 4]
l2 = ['a', 'b', 'c', 'd']
for i in list(itertools.product(l1, repeat = 2)):
    print(i)
</code></pre>

<p>The output is:</p>

<pre><code>(1, 1)
(1, 2)
...
</code></pre>

<p>I think this is very clear. But how can I manage to include the second list and get an output like this:</p>

<pre><code>(1, a),(1, a)
(1, a),(2, b)
(1, a),(3, c)
(1, a),(4, d)

(2, b),(1, a)
(2, b),(2, b)
(2, b),(3, c)
(2, b),(4, d)

(3, c),(1, a)
(3, c),(2, b)
(3, c),(3, c)
(3, c),(4, d)

(4, d),(1, a)
(4, d),(2, b)
(4, d),(3, c)
(4, d),(4, d)
</code></pre>

<p>I know that a proper solution would be to combine for-loops. But that doesn't fit for me as I want to increase the <code>repeat</code>-counter.</p>

<p>By providing a <code>zip</code> of the lists to <code>product</code>:</p>

<pre><code>for i in product(zip(l1,l2), repeat = 2):
    print(i)
</code></pre>

<p>Wrapping in a <code>list</code> isn't required, the for loop takes care of calling <code>next</code> on the iterator for you.</p>

<p>If you want a new-line for every 4 combinations, use <code>enumerate</code> (starting from <code>1</code>) and add a <code>\n</code> when <code>c % 4</code> is <code>0</code>:</p>

<pre><code>for c, i in enumerate(product(zip(l1,l2), repeat = 2), 1):
    print(i, '\n' if c % 4 == 0 else '')
</code></pre>

<p>Output:</p>

<pre><code>((1, 'a'), (1, 'a')) 
((1, 'a'), (2, 'b')) 
((1, 'a'), (3, 'c')) 
((1, 'a'), (4, 'd')) 

((2, 'b'), (1, 'a')) 
((2, 'b'), (2, 'b')) 
((2, 'b'), (3, 'c')) 
((2, 'b'), (4, 'd')) 

((3, 'c'), (1, 'a')) 
((3, 'c'), (2, 'b')) 
((3, 'c'), (3, 'c')) 
((3, 'c'), (4, 'd')) 

((4, 'd'), (1, 'a')) 
((4, 'd'), (2, 'b')) 
((4, 'd'), (3, 'c')) 
((4, 'd'), (4, 'd')) 
</code></pre>

python list python-3.x for-loop itertools