Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Set update() in Python to do union of n arrays
In this tutorial, we will use the set.update() method to find the union of multiple arrays. This method efficiently combines arrays while automatically removing duplicates, returning a one-dimensional array with all unique values.
What is set.update()?
The update() method adds elements from an iterable (like a list or array) to an existing set. It automatically handles duplicates by keeping only unique values.
Syntax
set.update(iterable)
Example
Let's see how to union multiple arrays using set.update() ?
# initializing the arrays
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 with elements from current array
result.update(array)
# converting set to list and printing
print(list(result))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
How It Works
The algorithm follows these steps:
- Create an empty set to store unique elements
- Iterate through each array in the input
- Use
update()to add elements from current array to the set - Convert the final set back to a list
Alternative Approach Using Union Operator
You can also use the union operator (|) for the same result ?
arrays = [[1, 2, 3, 4, 5], [6, 7, 8, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
result = set()
for array in arrays:
result = result | set(array)
print(list(result))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Comparison
| Method | Memory Usage | Performance | Readability |
|---|---|---|---|
update() |
Lower | Faster | Good |
Union operator |
|
Higher | Slower | Very Good |
Conclusion
The set.update() method provides an efficient way to union multiple arrays by automatically handling duplicates. It's memory-efficient and performs well for large datasets compared to other approaches.
