combining elements of 2 list in a certain way

55 Views Asked by At

i have a doubt in combining 2 lists into one in a certain way. can anyone help me out?

i have 2 lists

a = ['a', 'b', 'c', 'd', 'e']
b = [1, 2, 3]

i want the resultant list like ['a1', 'b2', 'c3', 'd1', 'e2'] The result list must be generated by iterating through the list a and simultaniously cycling through the list b.

i have tried the following code

r = ['%s%d' % item for item in zip(a,b)]

but the output I'm getting is,

['a1', 'b2', 'c3']

2

There are 2 best solutions below

0
On

You can use itertools.cycle to repeat the shortest list:

from itertools import cycle

out = [f'{x}{y}' for x, y in zip(a, cycle(b))]

If you don't know which of a/b is longest:

from itertools import cycle

out = [f'{x}{y}' for x, y in
       (zip(a, cycle(b)) if len(a)>len(b) else zip(cycle(a), b))]

Output: ['a1', 'b2', 'c3', 'd1', 'e2']

0
On

You can use the zip() function to iterate through the two lists simultaneously

a = ['a', 'b', 'c', 'd', 'e']
b = [1, 2, 3]

result = [x+str(y) for x, y in zip(a, b*len(a))]
print(result)