In Python, Sets are a data structure that allows us to store unique values in an unordered collection. Set operations are a common way to perform various tasks with sets. In this article, we will discuss some of the most commonly used set operations in Python.
1) Union (|): This operation combines two sets into one set and returns all the distinct values from both sets.
For example:
set1 = {1, 2, 3} set2 = {2, 3, 4} print(set1 | set2) # Output: {1, 2, 3, 4}
2) Intersection (&): This operation returns only the values that are common to both sets.
For example:
set1 = {1, 2, 3} set2 = {2, 3, 4} print(set1 & set2) # Output: {2, 3}
3) Difference (-): This operation returns the values that are belong to one set only but not belong to another set.
For example:
set1 = {1, 2, 3} set2 = {2, 3, 4} print(set1 - set2) # Output: {1} print(set2 - set1) # Output: {4}
4) Symmetric Difference (^): This operation returns the values that are unique to each set, but not both.
For example:
set1 = {1, 2, 3} set2 = {2, 3, 4} print(set1 ^ set2) # Output: {1, 4}
5) Subset (<=): This operation returns True if all elements of the first set are also present in the second set, otherwise returns False.
For example:
set1 = {1, 2} set2 = {1, 2, 3} print(set1 <= set2) # Output: True
6) Superset (>=): The superset operation returns True if all elements of the second set are also present in the first set, otherwise returns False.
For example:
set1 = {1, 2, 3} set2 = {1, 2} print(set1 >= set2) # Output: True
In conclusion, these are some of the most commonly used set operations in Python. By understanding and using these operations, we can perform various tasks with sets in a efficient manner.