Change language

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.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method