Home > Enterprise >  How to combine the elements of two lists using zip function in python?
How to combine the elements of two lists using zip function in python?

Time:02-12

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

CodePudding user response:

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)

CodePudding user response:

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")
  • Related