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

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

## Python Itertools: Exercise-25 with Solution

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]
```

Python Code Editor:

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

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.

﻿