How to Find Union of Two Sets in Python Quickly
To find the union of two sets in Python, use the
union() method or the | operator. Both combine all unique elements from both sets into a new set.Syntax
The union of two sets can be found using either the union() method or the | operator.
set1.union(set2): Returns a new set with all unique elements fromset1andset2.set1 | set2: Another way to get the union using the pipe operator.
python
union_set = set1.union(set2)
# or
union_set = set1 | set2Example
This example shows how to find the union of two sets using both the union() method and the | operator.
python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Using union() method
union1 = set1.union(set2)
# Using | operator
union2 = set1 | set2
print("Union using union():", union1)
print("Union using | operator:", union2)Output
Union using union(): {1, 2, 3, 4, 5}
Union using | operator: {1, 2, 3, 4, 5}
Common Pitfalls
Some common mistakes when finding the union of sets include:
- Using
+operator which does not work with sets. - Modifying one of the original sets unintentionally instead of creating a new set.
- Confusing union with intersection which finds common elements.
python
wrong_union = set1 + set2 # This will cause an error # Correct way: correct_union = set1.union(set2)
Quick Reference
| Operation | Syntax | Description |
|---|---|---|
| Union using method | set1.union(set2) | Returns a new set with all unique elements from both sets |
| Union using operator | set1 | set2 | Returns a new set with all unique elements from both sets |
| In-place union | set1.update(set2) | Adds elements from set2 into set1 (modifies set1) |
Key Takeaways
Use
union() or | to find the union of two sets in Python.The union operation returns a new set with all unique elements from both sets.
Avoid using
+ operator with sets as it causes errors.Use
update() if you want to add elements to an existing set instead of creating a new one.Union is different from intersection; union combines all elements, intersection finds common ones.