Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading