2

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']

pmqs
  • 3,066
  • 2
  • 13
  • 22

2 Answers2

3

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']

mozway
  • 194,879
  • 13
  • 39
  • 75
0

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)
executable
  • 3,365
  • 6
  • 24
  • 52