Keeping the structure of a list in after operating a nested loop

Question:

Suppose I have two lists as follow:

x = [['a','b','c'],['e','f']]
y = ['w','x','y']

I want to add each element of list x with each element of list y while keeping the structure as given in x the desired output should be like:

[['aw','ax','ay','bw','bx','by','cw','cx','cy'],['ew','ex','ey','fw','fx','fy']]

So far I’ve done:

res = []
for i in range(len(x)):
    for j in range(len(x[i])):
        for t in range(len(y)):
            res.append(x[i][j]+y[t])

where res produces the sums correctly but I am losing the structure, I get:

['aw','ax','ay','bw','bx','by','cw','cx','cy','ew','ex','ey','fw','fx','fy']

Also is there a better way of doing this instead of many nested loops?

Asked By: Wiliam

||

Answers:

The key here is to understand list comprehension and the difference between .extend() and .append() for python lists.

output = []
for el in x:
    sub_list = []
    for sub_el in el:
        sub_list.extend([sub_el+i for i in y])
    output.append(sub_list)

print(output)
Answered By: oscjac

With itertools.product and builtin map functions:

import itertools

x = [['a','b','c'], ['e','f']]
y = ['w','x','y']
res = [list(map(''.join, itertools.product(i, y))) for i in x]

print(res)

The output:

[['aw', 'ax', 'ay', 'bw', 'bx', 'by', 'cw', 'cx', 'cy'], ['ew', 'ex', 'ey', 'fw', 'fx', 'fy']]
Answered By: RomanPerekhrest

Hope this helps!

x = [['a','b','c'],['e','f']]
y = ['w','x','y']
out_put=[]
def helper(l1,l2):
    return [i+j for i in l1 for j in l2]

 

for i in x:
    out_put.append(helper(i,y))
Answered By: AlekhyaV – Intel