Python | Sum two unequal length lists in cyclic manner

Given two unequal length lists, the task is to add elements of two list such that when elements of smaller list are over, add elements in a circular manner till all element of the larger list is iterated.

Let’s discuss different ways we can do this task.

Method #1 : Using Iteratools and zip

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to add two different
# length lists in cyclic manner
  
# Importing
from itertools import cycle
  
# List initialization
list1 = [150, 177, 454, 126]
list2 = [9, 44, 2, 168, 66, 80, 123, 6, 180, 184]
  
# Using zip
output = [x + y for x, y in zip(cycle(list1), list2)]
  
# Printing output
print(output)

chevron_right


Output:

[159, 221, 456, 294, 216, 257, 577, 132, 330, 361]

 
Method #2 : Using Iteratools and starmap

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to add two different 
# length lists in cyclic manner
  
# Importing
from itertools import starmap, cycle
from operator import add
  
# List initialization
list1 = [150, 177, 454, 126]
list2 = [9, 44, 2, 168, 66, 80, 123, 6, 180, 184]
  
# Using starmap
output = list(starmap(add, zip(cycle(list1), list2)))
  
# Print output
print(output)

chevron_right


Output:

[159, 221, 456, 294, 216, 257, 577, 132, 330, 361]

 
Method #3 : Using List comprehension

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to add two different
# length lists in cyclic manner
  
# List initialization
list1 = [150, 177, 454, 126]
list2 = [9, 44, 2, 168, 66, 80, 123, 6, 180, 184]
  
# List comprehension
output = [list1[i % len(list1)]+list2[i]
             for i in range(len(list2))]
  
# Printing output
print(output)

chevron_right


Output:

[159, 221, 456, 294, 216, 257, 577, 132, 330, 361]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.