Python | Sum two unequal length lists in cyclic manner
Last Updated :
26 Apr, 2023
Given two unequal-length lists, the task is to add elements of two list such that when elements of the 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
Python3
# 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)
Output:[159, 221, 456, 294, 216, 257, 577, 132, 330, 361]
Method #2: Using Iteratools and starmap
Python3
# 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)
Output:[159, 221, 456, 294, 216, 257, 577, 132, 330, 361]
Method #3: Using List comprehension
Python3
# 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)
Output:[159, 221, 456, 294, 216, 257, 577, 132, 330, 361]
Method #4: Using a for loop
Approach:
- Initialize an empty list to store the output
- Determine the length of the longer list and use it as the range for the for loop
- In the for loop, add the elements from both lists cyclically and append the sum to the output list
- Print the output list
Below is the implementation of the above approach:
Python3
list1 = [150, 177, 454, 126]
list2 = [9, 44, 2, 168, 66, 80, 123, 6, 180, 184]
output = []
longer_length = max(len(list1), len(list2))
for i in range(longer_length):
sum = list1[i % len(list1)] + list2[i % len(list2)]
output.append(sum)
print(output)
Output[159, 221, 456, 294, 216, 257, 577, 132, 330, 361]
Time complexity: O(max(len(list1), len(list2)))
Auxiliary space: O(max(len(list1), len(list2))) for the output list
Method 5: Using the built-in map() function and lambda function.
Approach:
- Define a lambda function that takes two arguments x and y, and returns their sum.
- Use the cycle() function from the itertools module to create an iterator that cycles through the elements of list1 indefinitely.
- Use the map() function to apply the lambda function to each pair of corresponding elements from list1 and list2.
- Convert the resulting map object to a list and assign it to output.
- Print the output.
Python3
# Python code to add two different
# length lists in cyclic manner
from itertools import cycle
# List initialization
list1 = [150, 177, 454, 126]
list2 = [9, 44, 2, 168, 66, 80, 123, 6, 180, 184]
# Using map and lambda
def add(x, y): return x + y
# Adding 2 different length lists in cyclic manner
cycled_list1 = cycle(list1)
output = list(map(add, cycled_list1, list2))
# Printing output
print(output)
Output[159, 221, 456, 294, 216, 257, 577, 132, 330, 361]
Time complexity: O(n), where n is the length of the longer input list, because we need to iterate over all the elements of the longer list once.
Auxiliary space: O(n), because we create a new list to store the output.
Method 6: Using numpy
- Use numpy's array and tile functions to create arrays of the same length by repeating the elements of the shorter array.
- The max function is used to get the length of the longer array.
- The arrays are then added element-wise using the + operator.
- The tolist function is used to convert the numpy array back to a regular Python list.
Python3
import numpy as np
# List initialization
list1 = [150, 177, 454, 126]
list2 = [9, 44, 2, 168, 66, 80, 123, 6, 180, 184]
# Converting lists to numpy arrays
arr1 = np.array(list1)
arr2 = np.array(list2)
# Getting the length of the longer array
n = max(len(arr1), len(arr2))
# Reshaping the arrays to the same shape by
# repeating their elements
arr1 = np.tile(arr1, n//len(arr1) + 1)[:n]
arr2 = np.tile(arr2, n//len(arr2) + 1)[:n]
# Adding the arrays element-wise
output = arr1 + arr2
# Printing output
print(output.tolist())
Output
[159, 221, 456, 294, 216, 257, 577, 132, 330, 361]
Time complexity: O(n), where n is the length of the longer list (since we need to iterate over all elements of the longer list).
Auxiliary space: O(n), since we create two numpy arrays of length n.
Similar Reads
Python | Zipping two unequal length list in dictionary
Given two lists of possibly unequal lengths, the task is to zip two lists in a dictionary such that the list with shorter length will repeat itself. Since the dictionary in Python is an unordered collection of key:value pairs, the result will be printed on unordered fashion. Method #1: Using itertoo
4 min read
Python - Filter unequal elements of two lists corresponding same index
Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are unequal and have similar index. This kind of problem can come in many domains. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using
5 min read
Python - Pairs with Sum equal to K in tuple list
Sometimes, while working with data, we can have a problem in which we need to find the sum of pairs of tuple list. And specifically the sum that is equal to K. This kind of problem can be important in web development and competitive programming. Lets discuss certain ways in which this task can be pe
6 min read
Merge Two Lists into List of Tuples - Python
The task of merging two lists into a list of tuples involves combining corresponding elements from both lists into paired tuples. For example, given two lists like a = [1, 2, 3] and b = ['a', 'b', 'c'], the goal is to merge them into a list of tuples, resulting in [(1, 'a'), (2, 'b'), (3, 'c')]. Usi
3 min read
Python - Interleave two lists of different length
Given two lists of different lengths, the task is to write a Python program to get their elements alternatively and repeat the list elements of the smaller list till the larger list elements get exhausted. Examples: Input : test_list1 = ['a', 'b', 'c'], test_list2 = [5, 7, 3, 0, 1, 8, 4] Output : ['
3 min read
Python | Accumulative index summation in tuple list
Sometimes, while working with data, we can have a problem in which we need to find accumulative summation of each index in tuples. This problem can have applications in web development and competitive programming domain. Let's discuss certain way in which this problem can be solved. Method 1: Using
8 min read
Python - Interleave multiple lists of same length
When we interleave multiple lists, we mix the items from each list so that they alternate in a new sequence. This is often done when we have lists of the same length and want to combine them, with each item from each list appearing one after another. In this article, we will explore interleaving mul
2 min read
Python | Split a list into sublists of given lengths
The problem of splitting a list into sublists is quite generic but to split in sublist of given length is not so common. Given a list of lists and list of length, the task is to split the list into sublists of given length. Example: Input : Input = [1, 2, 3, 4, 5, 6, 7] length_to_split = [2, 1, 3, 1
2 min read
Python | Split nested list into two lists
Given a nested 2D list, the task is to split the nested list into two lists such that the first list contains the first elements of each sublist and the second list contains the second element of each sublist. In this article, we will see how to split nested lists into two lists in Python. Python Sp
5 min read
Python | Column summation in uneven sized lists
The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the summation of its columns, the uneven length of rows may lead to some elements in that element to be absent and if not handled correctly, may throw exception. L
7 min read