![]() |
VOOZH | about |
Sometimes, while working with Python records, we can have a problem in which we need to perform cross-summation of list of tuples. This kind of application is popular in web development domain. Let's discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + zip() The combination of above functionalities can be used to perform this particular task. In this, we iterate through the list using list comprehension and the summation across lists is performed with help of zip().
The original list 1 : [(2, 4), (6, 7), (5, 1)] The original list 2 : [(5, 4), (8, 10), (8, 14)] The Summation across lists is : [(7, 8), (14, 17), (13, 15)]
Time complexity: O(n), where n is the length of the input lists
Auxiliary space: O(n), where n is the length of the input lists.
Method #2 : Using sum() + zip() + map() This is yet another way to perform this task. This is similar to above method, the difference is that summation is performed by inbuilt function and extending logic to each element is done by map().
The original list 1 : [(2, 4), (6, 7), (5, 1)] The original list 2 : [(5, 4), (8, 10), (8, 14)] The Summation across lists is : [(7, 8), (14, 17), (13, 15)]
Time complexity: O(n), where n is the length of the lists.
Auxiliary space: O(n), as the resulting list res has the same length as the input lists.
Method #3: Using numpy
Note: Install numpy module using command "pip install numpy"
The numpy library in python provides a function called numpy.add() which can be used to perform the cross summation of two lists of tuples.
Output:
The original list 1 : [(2, 4), (6, 7), (5, 1)] The original list 2 : [(5, 4), (8, 10), (8, 14)] The Summation across lists is : [(7, 8), (14, 17), (13, 15)]
Time complexity: O(n) where n is the size of the lists.
Auxiliary Space: O(n)
Method #4: Using a for loop:
The original list 1 : [(2, 4), (6, 7), (5, 1)] The original list 2 : [(5, 4), (8, 10), (8, 14)] The Summation across lists is : [(7, 8), (14, 17), (13, 15)]
Time complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using a lambda function with map() and zip()
The Summation across lists is : [(7, 8), (14, 17), (13, 15)]
Time Complexity: O(n), where n is the length of the input lists test_list1 and test_list2.
Auxiliary Space: O(n), where n is the length of the input lists test_list1 and test_list2.
Method #11: Using the itertools module's starmap() function
The original list 1 : [(2, 4), (6, 7), (5, 1)] The original list 2 : [(5, 4), (8, 10), (8, 14)] The Summation across lists is : [(7, 8), (14, 17), (13, 15)]
Time complexity: O(n), where n is the length of the input lists
Auxiliary space: O(n), for storing the output list