- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
# 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.
Advertisements