w3resource

Python: Find the first two elements of a given list whose sum is equal to a given value


25. First Two Sum Elements

Write a Python program to find the first two elements of a given list whose sum is equal to a given value. Use the itertools module to solve the problem.

Sample Solution:

Python Code:

import itertools as it
def sum_pairs_list(nums, n):
    for num2, num1 in list(it.combinations(nums[::-1], 2))[::-1]:
        if num2 + num1 == n:
            return [num1, num2]

nums = [1,2,3,4,5,6,7]     
n = 10
print("Original list:",nums,": Given value:",n)   
print("Sum of pair equal to ",n,"=",sum_pairs_list(nums,n))

nums = [1,2,-3,-4,-5,6,-7]     
n = -6
print("Original list:",nums,": Given value:",n)   
print("Sum of pair equal to ",n,"=",sum_pairs_list(nums,n))

Sample Output:

Original list: [1, 2, 3, 4, 5, 6, 7] : Given value: 10
Sum of pair equal to  10 = [4, 6]
Original list: [1, 2, -3, -4, -5, 6, -7] : Given value: -6
Sum of pair equal to  -6 = [1, -7]

For more Practice: Solve these Related Problems:

  • Write a Python program to find the first pair of consecutive elements in a list that sum to a given value using itertools.combinations.
  • Write a Python program to iterate over a list and return the first two numbers whose sum equals a target, using a sliding window approach.
  • Write a Python program to generate pairs from a list and then filter to find the first pair that matches the given sum.
  • Write a Python program to use itertools to produce adjacent pairs from a list and then return the first pair with a sum equal to a specified value.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find the maximum length of a substring in a given string where all the characters of the substring are same. Use itertools module to solve the problem.

Next: Write a Python program to find the nth Hamming number. User itertools module.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.