Set update () in Python to concatenate n arrays



Examples:

 Input: arr = [[1, 2, 2, 4, 3, 6], [5, 1, 3, 4], [9, 5, 7, 1] , [2, 4, 1, 3]] Output: [1, 2, 3, 4, 5, 6, 7, 9] 

Simple solution this problem is to create an empty hash and traverse each array one by one, this hash contains the frequency of each element in the list of arrays. Now look at the hash from the beginning and print every index that has a nonzero value.

Here we solve this problem very quickly in python using the data structure properties Set () and Update () method in python.

How does Update () method work for set?

anySet.update (iterable) , this method performs the concatenation of a set named as anySet with any given iterable and it does not return a shallow copy of the set like the union () method, it updates the result in the ie prefix set;  anySet .

# Function for joining n arrays

  

def combineAll ( input ):

 

  # cast the first array as set and assign it

  # to the variable named as result

result = set ( input [ 0 ])

  

  # now traverse the remaining array list

# and take it with the result variable

for array in input [ 1 :]:

result.update (array)

  

return list (result)

 
# Driver program

if __ name__ = = "__ main__" :

input = [[ 1 , 2 , 2 , 4 , 3 , 6 ], [ 5 , 1 , 3 , 4 ],

[ 9 , 5 , 7 , 1 ], [ 2 , 4 , 1 , 3 ]] 

  print combineAll ( input )

Output:

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

This article courtesy of Shashank Mishra (Gullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you`d like to share more information on the topic discussed above.