How can I combine 2 lists in a specific order?

Question:

This is an example for 3 elements

List_A = ['abc', 'def', 'ghi']
List_B = ['123', '456', '789']


for i in [List_A[0], List_B[0]]:
    for j in [List_A[1], List_B[1]]:
        for k in [List_A[2], List_B[2]]:
            print(i+j+k)

Following this result:

abcdefghi
abcdef789   
abc456ghi
abc456789
123defghi
123def789
123456ghi
123456789

How would be a code with a general application to produce the same result as:

for i in [List_A[0], List_B[0]]:
    for j in [List_A[1], List_B[1]]:
        for k in [List_A[2], List_B[2]]:
                ...
              for z in [List_A[n], List_B[n]]:
                   print(i+j+k+...+z)

with
len(List_A) == len(List_B) == n?

I think there is some relation with recursion algorithms. I tried some functions of itertools, and I didn’t succeeded.

Asked By: Fabricio Brum

||

Answers:

Do you want something like?

import itertools
print(["".join(i) for i in itertools.product(*zip(a, b))])

which gives

['abcdefghi',
 'abcdef789',
 'abc456ghi',
 'abc456789',
 '123defghi',
 '123def789',
 '123456ghi',
 '123456789']
Answered By: tomjn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.