Python Find Union and Intersection of Two sorted Arrays

To find union and intersection of two sorted arrays in python; Through this tutorial, i am going to show you how to find union and intersection of two sorted arrays in python.

Union:- A list that has the common distinct element from both arrays and if there are repetitions of the element then only one occurrence is considered, known as the union of both arrays.

Intersection:- A list that has common distinct elements from both arrays, is the intersection of both arrays.

Python Program to Find Union and Intersection of Two sorted Arrays

  • Get input Two arrays from the user in the program.
  • Find the union and intersection of these arrays bitwise operators.
  • Store result in different variables.
  • Print result.
# Program to find the union and intersection of two arrays
#take input two array from user
firstArr=list(map(int,input('Enter elements of first list:').split()))
secondArr=list(map(int,input('Enter elements of second list:').split()))
# find the union and intersection of two arrays 
#using bitwise operators
x=list(set(firstArr)|set(secondArr))
y=list(set(firstArr)&set(secondArr))
#print list
print('Union of the arrays:',x)
print('intersection of the arrays:',y)

After executing the program, the output will be:

Enter elements of first list: 2 5 6 
Enter elements of second list: 5 7 9 6
Union of the arrays: [2, 5, 6, 7, 9]
intersection of the arrays: [5, 6]

Recommended Python Tutorials

Leave a Comment