Set update() in Python to do union of n arrays


In this tutorial, we are going to write a program that uses set update method to union multiple arrays. And it will return a resultant one-dimension array with all unique values from the arrays.

Let's see an example to understand it more clearly.

Let's see an example to understand it more clearly.

Input

arrays = [[1, 2, 3, 4, 5], [6, 7, 8, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

Output

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

Follow the below steps to write the program.

  • Initialize the array as shown in the example.
  • 3Create an empty.
  • Iterate over the arrays.
  • In each iteration, use the update method of the set to add new unique elements to the
  • Convert the set to list and print it.

Example

 Live Demo

# initialzing the array
arrays = [[1, 2, 3, 4, 5], [6, 7, 8, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6, 7, 8, 9,10]]
# empty set
result = set()
# iterating over the arrays
for array in arrays:
   # updating the set
   result.update(array)
# converting and printing the set in list
print(list(result))

Output

If you run the above code, then you will get the following result.

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

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Updated on: 11-Jul-2020

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements