user10255809
user10255809

Reputation:

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:

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

but this gives an output:

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

Upvotes: 0

Views: 407

Answers (1)

C.Nivs
C.Nivs

Reputation: 13106

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

Upvotes: 1

Related Questions