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

How to append element of same index from a list to another list multiple times?

I have 2 lists of equal lengths as follows


list1 = ['23, 42, 52', '4, 3, 6']
list2 = ['foo', 'bar']

How do I make a single list with the desired outcome be:

list = ['23foo, 42foo, 52foo', '4bar, 3bar, 6bar']

I have tried:

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

list= [i + j for i, j in zip(list1, list2)]

but this gives an output:

list = ['23, 42, 52foo', '4, 3, 6bar']

>Solution :

You’ll want:

list3 = [', '.join((f"{i}{j}" for i in k.split(', '))) for k, j in zip(list1, list2)]

print(list3)

['23foo, 42foo, 52foo', '4bar, 3bar, 6bar']

Because you need to split up the first string before you can add the desired suffix to it. Then, re-join the split string together.

Also, try not to shadow list, it’s a built-in, so list3 is a better name for it

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