Join sets in Python
Introduction to Sets in Python
In Python, a set is an unordered collection of unique elements. Sets are created using the set class. They are useful for performing mathematical operations such as union, intersection, difference, and symmetric difference.
Creating a Set
# Creating two sets set1 = {1, 2, 3, 4, 5} set2 = set([4, 5, 6, 7, 8])
Union of Two Sets
The union of two sets is a set containing all elements from both sets, with no duplicates.
union() Method
union_set = set1.union(set2) print(union_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
| Operator
union_set = set1 | set2 print(union_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
Union of Multiple Sets
You can perform a union operation on multiple sets in one go.
set3 = {9, 10} set4 = {11, 12} union_multiple = set1.union(set2, set3, set4) print(union_multiple) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Joining a Set with a Tuple
You can add elements from a tuple to a set.
tuple_ = (13, 14, 15) set1.update(tuple_) print(set1) # Output: {1, 2, 3, 4, 5, 13, 14, 15}
Updating a Set
The update() method allows you to add multiple elements to a set. This can be done with lists, sets, or tuples.
set1.update([16, 17], {18, 19}) print(set1) # Output: {1, 2, 3, 4, 5, 13, 14, 15, 16, 17, 18, 19}
Intersection of Two Sets
The intersection of two sets is a set containing elements common to both sets.
intersection() Method
intersection_set = set1.intersection(set2) print(intersection_set) # Output: {4, 5}
& Operator
intersection_set = set1 & set2 print(intersection_set) # Output: {4, 5}
Difference between Two Sets
The difference between two sets is a set containing elements that are in the first set but not in the second.
difference() Method
difference_set = set1.difference(set2) print(difference_set) # Output: {1, 2, 3, 13, 14, 15}
– Operator
difference_set = set1 - set2 print(difference_set) # Output: {1, 2, 3, 13, 14, 15}
Symmetric Difference between Two Sets
The symmetric difference between two sets is a set containing elements that are in either set, but not in both.
symmetric_difference() Method
sym_diff_set = set1.symmetric_difference(set2) print(sym_diff_set) # Output: {1, 2, 3, 6, 7, 8, 13, 14, 15}
^ Operator
sym_diff_set = set1 ^ set2 print(sym_diff_set) # Output: {1, 2, 3, 6, 7, 8, 13, 14, 15}
Summary of Set Methods and Operators
- Union: Use union() or the | operator
- Update: Use update()
- Intersection: Use intersection() or the & operator
- Difference: Use difference() or the – operator
- Symmetric Difference: Use symmetric_difference() or the ^ operator