Open In App

Python – K Summation from Two lists

Last Updated : 03 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists we can have a problem in which we need to find summation of lists taking elements from two different lists. This kind of application can come in different domains such as web development. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using loop This task can be done using loop in a brute force manner. We run a nested loop one for each list and when we find a match we update the result list with the pair. 

Python3




# Python3 code to demonstrate
# K Summation from Two lists
# using loop
 
# Initializing lists
test_list1 = [3, 2, 5]
test_list2 = [4, 3, 6, 8, 7]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Initializing K
K = 9
 
# K Summation from Two lists
# using loop
res = []
for idx in test_list1:
    val_req = K - idx
    for j in test_list2:
        if j == val_req:
            x, y = j, idx
            res.append((x, y))
 
# printing result
print ("Summation pairs among lists : " + str(res))


Output : 

The original list 1 is : [3, 2, 5]
The original list 2 is : [4, 3, 6, 8, 7]
Summation pairs among lists : [(6, 3), (7, 2), (4, 5)]

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.

Method #2 : Using list comprehension This is yet another way in which this task can be performed. In this, we perform similar task as above. The difference is that this is one liner and we perform task in one line. 

Python3




# Python3 code to demonstrate
# K Summation from Two lists
# using list comprehension
 
# Initializing lists
test_list1 = [3, 2, 5]
test_list2 = [4, 3, 6, 8, 7]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Initializing K
K = 9
 
# K Summation from Two lists
# using list comprehension
res = [(a, b) for a in test_list1 for b in test_list2 if a + b == K]
 
# printing result
print ("Summation pairs among lists : " + str(res))


Output : 

The original list 1 is : [3, 2, 5]
The original list 2 is : [4, 3, 6, 8, 7]
Summation pairs among lists : [(6, 3), (7, 2), (4, 5)]

Method #3 :  Here is another approach using dictionaries to store elements of one list as keys and their difference with K as values. Then we iterate over the second list and check if the difference is present in the dictionary. If yes, we add the pair to the result list.

Python3




# Python3 code to demonstrate
# K Summation from Two lists
# using dictionaries
   
# Initializing lists
test_list1 = [3, 2, 5]
test_list2 = [4, 3, 6, 8, 7]
   
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
   
# Initializing K
K = 9
   
# K Summation from Two lists
# using dictionaries
d = {}
for i in test_list1:
    d[i] = K - i
     
res = [(val, key) for key in d.keys() for val in test_list2 if key + val == K and val in d.values()]
   
# printing result
print ("Summation pairs among lists : " + str(res))


Output

The original list 1 is : [3, 2, 5]
The original list 2 is : [4, 3, 6, 8, 7]
Summation pairs among lists : [(6, 3), (7, 2), (4, 5)]

Time Complexity: O(n), where n is the length of the longer list.
Auxiliary Space: O(n), as we are storing elements of one list in a dictionary.

Method #4 : Using  map() and filter():

Python3




test_list1 = [3, 2, 5]
test_list2 = [4, 3, 6, 8, 7]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
K = 9
result = list(filter(lambda x: x[0] + x[1] == K, map(lambda x: (x[1], x[0]), [(a, b) for a in test_list1 for b in test_list2])))
print("Summation pairs among lists : ", result)
#This code is contributed by Jyothi pinjala.


Output

The original list 1 is : [3, 2, 5]
The original list 2 is : [4, 3, 6, 8, 7]
Summation pairs among lists :  [(6, 3), (7, 2), (4, 5)]

Time Complexity: O(n^2)
Auxiliary Space: O(n)

Method #5: Using itertools.product() and filter()

  • The itertools module is imported, which provides a set of tools for iterating over iterators.
  • The product() function from the itertools module is used to find the Cartesian product of test_list1 and test_list2, which will generate all possible combinations of pairs of elements from the two lists. The product() function returns an iterator of tuples, where each tuple contains one element from test_list1 and one element from test_list2.
  • A lambda function is defined as an argument to the filter() function. The lambda function takes a tuple as input, calculates the sum of the tuple’s elements, and returns True if the sum equals K.
  • The filter() function filters out tuples from the iterator returned by product() that do not satisfy the condition of having a sum equal to K. The filtered tuples are collected into a list using the list() function.
    The list of tuples with a sum equal to K is stored in the variable res.
  • Finally, the result is printed using the print() function. The str() function is used to convert the list of tuples to a string for printing.

Python3




import itertools
 
# Initializing lists
test_list1 = [3, 2, 5]
test_list2 = [4, 3, 6, 8, 7]
 
# Initializing K
K = 9
 
# K Summation from Two lists using itertools.product() and filter()
res = list(filter(lambda pair: sum(pair) == K, itertools.product(test_list1, test_list2)))
 
# printing result
print("Summation pairs among lists : " + str(res))


Output

Summation pairs among lists : [(3, 6), (2, 7), (5, 4)]

Time complexity: O(n^2) since it generates all possible pairs between the two input lists.
Auxiliary space: O(1) since it only stores the final result in memory.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads