Skip to content
Advertisement

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

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?

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement