1

I have two lists:

a = [50, 17, 54, 26]
b = [19,  7,  8, 18, 36, 8, 18, 36, 18, 14]

I want to add to the elements of b the corresponding elements of a. When the elements of a runs out, I want to cycle through a to supply the elements. The result should be:

c = [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]

What is the "Pythonic" way to implement this?

yatu
  • 86,083
  • 12
  • 84
  • 139
Baxter
  • 142
  • 6

2 Answers2

10

You could use a list comprehension to add the elements from both lists zipped together, and use itertools.cycle so that the iterator a repeats itself as many times as necessary until b is exhausted:

from itertools import cycle
a = [50, 17, 54, 26]
b = [19,  7,  8, 18, 36, 8, 18, 36, 18, 14]

[i+j for i,j in zip(cycle(a), b)]

Output

[69, 24, 62, 44, 86, 25, 72, 62, 68, 31]

Details

If you take a look at the iterator of tuples generated from the zipped expression:

list(zip(cycle(a),b))

[(50, 19),
 (17, 7),
 (54, 8),
 (26, 18),
 (50, 36),
 (17, 8),
 (54, 18),
 (26, 36),
 (50, 18),
 (17, 14)]

You can see that the elements in a cycle around until the other iterator is exhausted, making it very easy to perform some operation on the interleaved elements.

yatu
  • 86,083
  • 12
  • 84
  • 139
1

If you dont want any imports you can use the modulo operator (%).

a = [50, 17, 54, 26]
b = [19, 7, 8, 18, 36, 8, 18, 36, 18, 14]
[a[i%len(a)]+b[i] for i in range(len(b))]

Output

[69, 24, 62, 44, 86, 25, 72, 62, 68, 31]
DannyDannyDanny
  • 838
  • 9
  • 26