Python - Union of two or more Lists
Last Updated :
05 Dec, 2024
The union of two or more lists combines all elements ensuring no duplicates if specified. In this article we will explore various methods to get a union of two lists.
Using set.union
(Most Efficient for Uniqueness)
The union()
method ensures that the resulting list contains unique elements. Here we convert the lists to sets perform a union and convert back to a list. This approach automatically removes duplicates.
Python
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
# Find the union of lists
union_list = list(set(a).union(b))
print("Union lists:", union_list)
OutputUnion lists: [1, 2, 3, 4, 5, 6]
Let's see some other methods on how to do union of two more lists.
Using '|'
Operator for Sets
The '|
'operator is shorthand for the union operation between sets. It is similar to set.union()
but it's more concise. This will removes duplicates automatically and combines the lists.
Python
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
# Find the union of lists
union_list = list(set(a) | set(b))
print("Union lists:", union_list)
OutputUnion lists: [1, 2, 3, 4, 5, 6]
Using List Concatenation (Includes Duplicates)
Using list concatenation will simply combines all elements without removing duplicates. We can use this approach if duplicate elements are acceptable.
Python
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
# Concatenate the lists
union_list = a + b
print(union_list)
Output[1, 2, 3, 4, 3, 4, 5, 6]
Using List Comprehension
This method combines the lists and removes duplicates manually. Here we combines the lists and removes duplicates using set()
.
Python
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
# Find unique union using list comprehension
union_list = list(set([x for x in a + b]))
print(union_list)
Using NumPy's union1d()
for Numerical Lists
NumPy provides an optimized method to compute the union of arrays.
Python
import numpy as np
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
# Find the union of lists
union_list = np.union1d(a, b)
print("Union of lists:", union_list)
OutputUnion of lists: [1 2 3 4 5 6]
Explanation:
- NumPy’s
union1d()
function returns a sorted array with unique elements from the input arrays. - More Suitable for numerical data and large datasets.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice