Python Program to find the intersection of two list


April 10, 2022, Learn eTutorial
1370

What is the intersection of lists?

In this simple python program, we have to find the intersection of two lists or arrays. The intersection is just the opposite of union. In union, we are taking every element which is present in any of the list, but at the intersection of the list, we are just taking the elements which will be present in both the list.

Let us take an example to understand the concept. Set A={ 1, 2, 3, 4} and set B = {3, 4, 5, 6}, then the intersection of the two sets A and B will be denoted by I = {3, 4} the elements which present in both the list.

How is the intersection done in python?

Now let us check how we implement the intersection in a python programming language. After initializing the two lists, we add the elements in both lists using for loop and append operator in python language. We are then using a user-defined function to get the intersection elements, where we are doing an operation to get the elements common in both lists.

Note: We are using the set() built-in function in the python language. set() is a built-in function that is used to convert an iterable into a set of iterable elements, which are normally called a set. set() takes only one parameter and return the set of iterable sequence.

ALGORITHM

STEP 1: Define the main function in python programming.

STEP 2: Use the two lists and initialize both lists.

STEP 3: Accept the number of elements needed in both the list using python syntax.

STEP 4: Open the for loop to add the elements into the list one using the append operator.

STEP 5: Using print statement print, "the intersection is."

STEP 6: Call the user-defined function to do the intersection and print the return value in python.

USER DEFINED FUNCTION

STEP 1: Define the function and receive the lists as a parameter.

STEP 2: Return the value from the and operation of the set() values. set() is described in the above section.

Python Source Code

                                          def intersection(a, b):
    return list(set(a) & set(b))
 
def main():
    alist=[]
    blist=[]
    n1=int(input("Enter number of elements for list 1:"))
    n2=int(input("Enter number of elements for list 2:"))
    print("For list1:")
    for x in range(0,n1):
        element=int(input("Enter element:"))
        alist.append(element)
    print("For list2:")
    for x in range(0,n2):
        element=int(input("Enter element:"))
        blist.append(element)
    print("The intersection is :")
    print(intersection(alist, blist))
main()
                                      

OUTPUT

Enter number of elements for list 1: 3
Enter number of elements for list 2: 4
For list1:
Enter element: 3
Enter element: 2
Enter element: 6
For list2:
Enter element: 3
Enter element: 6
Enter element: 4
Enter element: 8
The intersection is :
[3, 6]