1

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
Swift Dev Journal
  • 19,282
  • 4
  • 56
  • 66
curd_C
  • 71
  • 2
  • 7
  • Does this answer your question? [Cartesian product of two lists in python](https://stackoverflow.com/questions/52192855/cartesian-product-of-two-lists-in-python) – buran Feb 11 '22 at 21:01
  • Also https://stackoverflow.com/q/533905/4046632 – buran Feb 11 '22 at 21:01
  • As mentioned in my question, I need to use the zip() function. I checked other questions on this platform, but couldn't find one that utilizes the zip function to achieve the same goal – curd_C Feb 11 '22 at 21:04
  • You may want to use zip, however it doesn't help in this case. `itertools.product` is the tool. You may want to elaborate further what you need zip for. Otherwise this is XY problem. – buran Feb 11 '22 at 21:05
  • Could you elaborate more on the "parallel execution" part? I don't know about everyone else but I have troubles understanding why double loop doesn't work out for you. – Karashevich B. Feb 11 '22 at 21:09

2 Answers2

2

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)
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

Honestly I think you wont be able to do it with zip because you are searching for another behaviour. To use syntactic sugar and make it work with zip will just void your debugging experience.

But if you would drag me by the knee:

zip([val for val in l1 for _ in range(len(l2))],
    [val for _ in l1 for val in l2])

where you first duplicate the first list to get xxxyyyzzz and duplicate the second list with abcabcabc

or

for last,first in [(l,f) for l in lasts for f in firsts]:
     print(last, first, "\n")