by BehindJava

Write a program to find the Intersection of Two Lists in Python

Home » python » Write a program to find the Intersection of Two Lists in Python

In this tutorial we are going to learn about finding the Intersection of two Lists in Python.

Python Program to Find the Intersection of Two Lists

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

Explanation

  1. User must enter the number of elements in the list and store it in a variable.
  2. User must enter the values to the same number of elements into the list.
  3. The append function obtains each element from the user and adds the same to the end of the list as many times as the number of elements taken.
  4. The same of 2 and 3 is done for the second list also.
  5. The intersection function accepts two lists and returns the list which is the intersection of the two lists, i.e, all the common values from list 1 and 2.
  6. The set function in the intersection function accepts a list and returns the list which contains the common elements in both the lists.
  7. The lists are passed to the intersection function and the returned list is printed.