How to Find Union of Array in Python : Only 4 Steps

How to Find Union of Array in Python

You can easily find the unique elements in an array in python when you union the two arrays. It allows you to remove any duplication of the array. In this post you will know how to find the union of array in python using steps.

Steps to find the union of arrays in python

Lets know all the steps to find the union of arrays in python.

Step 1: Create a sample array

The first step is to create a sample arrays that will used for implementing union on the arrays. Here I have created only two arrays. Use the below line of code to create an array.

array1 = [1, 2, 3, 4, 5]
array2 = [4, 5, 6, 7, 8]

Step 2: Create a set

Now the next step is to create set for each of the array. It is done because union operation is done on set only. You can convert the array to set using the set() function.

Add the below lines of code to convert these two arrays to set.

set1 = set(array1)
set2 = set(array2)

Step 3: Find the union of the set

After converting the array to set you can use the ” | ” to find the union of the two arrays. After that you will also convert the result to the list using the list() function.

Use the below line of code to achieve the above step.

union_list = list(union_set)

Step 4: Display the result

Now the last step is to display the result. Obviously to do that you will call the print() function.

print(union_array)

Below is the full code for the above steps.

array1 = [1, 2, 3, 4, 5]
array2 = [4, 5, 6, 7, 8]
set1 = set(array1)
set2 = set(array2)
union_set = set1 | set2
union_list = list(union_set)
print(union_list)

Output

[1, 2, 3, 4, 5, 6, 7, 8]

Conclusion

In this tutorial you have learned first to convert the array to the set and then using the ” | ” union operator found the union of two array. I hope the above steps has helped you in finding the union of the two array. If you have any other methods that can be used to find the union then you can message on Data Science Learner facebook page.

If you have any doubt then you can contact us for more help. We are always ready to our valuable readers like you. If you have

 

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner