I have two different lists and I would like to know how I can get each element of one list print with each element of another list. I know I could use two for loops (each for one of the lists), however I want to use the zip() function because there's more that I will be doing in this for loop
for which I will require parallel iteration.
I therefore attempted the following but the output is as shown below.
lasts = ['x', 'y', 'z']
firsts = ['a', 'b', 'c']
for last, first in zip(lasts, firsts):
print (last, first, "\n")
Output:
x a
y b
z c
Expected Output:
x a
x b
x c
y a
y b
y c
z a
z b
z c
I believe the function you are looking for is itertools.product:
lasts = ['x', 'y', 'z']
firsts = ['a', 'b', 'c']
from itertools import product
for last, first in product(lasts, firsts):
print (last, first)
x a
x b
x c
y a
y b
y c
z a
z b
z c
Another alternative, that also produces an iterator is to use a nested comprehension:
iPairs=( (l,f) for l in lasts for f in firsts)
for last, first in iPairs:
print (last, first)
If you must use zip(), both inputs must be extended to the total length (product of lengths) with the first one repeating items and the second one repeating the list:
iPairs = zip( (l for l in lasts for _ in firsts),
(f for _ in lasts for f in firsts) )