OneBite.Dev - Coding blog in a bite size

find the union of two arrays in python

Code snippet on how to find the union of two arrays in python

def union(a, b): 
    x = list(set(a) | set(b)) 
    return x 
  
a = [3,4,5] 
b = [4,5,6,7] 
  
print(union(a, b)) 

This code finds the union of two arrays in Python. STEP 1: the ‘def’ statement is used to define a function. Here, it is named ‘union’. The two arrays are represented as ‘a’ and ‘b’, which are passed as arguments in the function. STEP 2: ‘set’ is used on both the arrays to make sure that there are no duplicates in the resulting list. STEP 3: ’|’ is the union operator used to combine the two sets. An empty list is created to store the union of the two sets. STEP 4: The function returns the list of union. STEP 5: The two arrays are declared with values and the function is called by passing the two arrays as arguments. STEP 6: Finally, the result is printed.

python