How to use the built-in map() function and lambda function. In Python
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.
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 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.
Contact Us