8. Problem to find the combination of 2 elements from the list.

In this program, we will take a user input as a list and print the combination of 2 elements whose sum is 10 with the help of the below-given steps.

Combination of 2 elements:

Steps to solve the program
  1. Take a list as input and create an empty list.
  2. Import itertools.
  3. With the help of for loop and itertools.combinations check for combinations from the given list whose sum is 10.
  4. Add such combinations to the empty list.
  5. Print the list to see the combination of 2 elements.
				
					#Importing itertools
import itertools

#Input list
list1 = [2,5,8,5,1,9]

#Creating variable
var = 10

#Creating empty list
list3 = []

for i in range(len(list1)):
    for combi in itertools.combinations(list1,i):
        if sum(combi) == var:
            list3.append(combi)

#Printing output
print(list3)
				
			

Output :

				
					[(2, 8), (5, 5), (1, 9)]
				
			

Related Articles

Remove all duplicate elements

Squares of all even numbers

Leave a Comment