![]() |
VOOZH | about |
Given two or more lists, the task is to combine all elements into a single list. If unique elements are required, duplicates must be removed while forming the union. For Example:
Input: a = [1, 2, 3], b = [3, 4, 5]
Output: [1, 2, 3, 4, 5]
Let's explore different methods to find union of two list in Python.
set.union() merges multiple sets and returns all unique values. By converting lists into sets and applying union(), duplicates are removed automatically.
[1, 2, 3, 4, 5, 6]
Explanation:
| Operator The | operator performs the same operation as set.union() but in a shorter form. Both sets are merged, and duplicate values are removed automatically.
[1, 2, 3, 4, 5, 6]
Explanation:
For numerical lists, NumPy provides a highly optimized union method union1d(). It returns sorted unique elements from both lists.
[1 2 3 4 5 6]
Explanation: np.union1d(a, b) merges both inputs.
This method simply combines both lists without removing duplicates.
[1, 2, 3, 4, 3, 4, 5, 6]