Q:

Generate lists from matrix with the same index

I have a matrix that has 'N' lists, each list has 3 strings, that each string has 'M' characters. 
For example, N=3 (3 lists) and M=3 (all the strings are 3 characters):
M = [['123', '456', '789'], ['abc', 'def', 'ghi'], ['ABC', 'DEF', 'GHI']]

I need to generate lists of the same index values, let me show you the output:
['1aA', '2bB', '3cC']
['1aD', '2bE', '3cF']
['1aG', '2bH', '3cI']

['1dA', '2eB', '3fC']
['1dD', '2eE', '3fF']
['1dG', '2eH', '3fI']

['1gA', '2hB', '3iC']
['1gD', '2hE', '3iF']
['1gG', '2hH', '3iI']

['4aA', '5bB', '6cC']
['4aD', '5bE', '6cF']
['4aG', '5bH', '6cI']

['4dA', '5eB', '6fC']
['4dD', '5eE', '6fF']
['4dG', '5eH', '6fI']

['4gA', '5hB', '6iC']
['4gD', '5hE', '6iF']
['4gG', '5hH', '6iI']

['7aA', '8bB', '9cC']
['7aD', '8bE', '9cF']
['7aG', '8bH', '9cI']

['7dA', '8eB', '9fC']
['7dD', '8eE', '9fF']
['7dG', '8eH', '9fI']

['7gA', '8hB', '9iC']
['7gD', '8hE', '9iF']
['7gG', '8hH', '9iI']

Do you have any suggestion how should I do it? 

A:

One way to approach this problem is to take the cartesian product of all strings using itertools.product, and for each product, pick the items at the same index and make a string out of them using zip
from itertools import product

M = [['123', '456', '789'], ['abc', 'def', 'ghi'], ['ABC', 'DEF', 'GHI']]

output = []

#Take product of all elements
for lst in product(*M):

    #Take the characters at the same index and make a string out of them via zip
    res = [''.join(item) for item in zip(*lst)]

    #Append that list to final output
    output.append(res)

for item in output:
    print(item)

The output will be
['1aA', '2bB', '3cC']
['1aD', '2bE', '3cF']
['1aG', '2bH', '3cI']
['1dA', '2eB', '3fC']
['1dD', '2eE', '3fF']
['1dG', '2eH', '3fI']
['1gA', '2hB', '3iC']
['1gD', '2hE', '3iF']
['1gG', '2hH', '3iI']
['4aA', '5bB', '6cC']
['4aD', '5bE', '6cF']
['4aG', '5bH', '6cI']
['4dA', '5eB', '6fC']
['4dD', '5eE', '6fF']
['4dG', '5eH', '6fI']
['4gA', '5hB', '6iC']
['4gD', '5hE', '6iF']
['4gG', '5hH', '6iI']
['7aA', '8bB', '9cC']
['7aD', '8bE', '9cF']
['7aG', '8bH', '9cI']
['7dA', '8eB', '9fC']
['7dD', '8eE', '9fF']
['7dG', '8eH', '9fI']
['7gA', '8hB', '9iC']
['7gD', '8hE', '9iF']
['7gG', '8hH', '9iI']

Or a one-liner using list comprehension
output = [[''.join(item) for item in zip(*lst)] for lst in product(*M)]

