Python Set Operations and Functions
Python Set Operations and Functions
1. Set Union: The union of two sets is the set of all the elements of both the sets without duplicates.
Example:
>>> first_set.union(second_set)
{1, 2, 3, 4, 5}
2. Set Intersection: The intersection of two sets is the set of all the common elements of both the
sets.
Example:
>>> first_set.intersection(second_set)
{4, 5, 6}
3. Set Difference: The difference between two sets is the set of all the elements in first set that are
Example:
>>> first_set.difference(second_set)
{1, 2, 3}
{8, 9, 7}
4. Set Symmetric Difference: The symmetric difference between two sets is the set of all the
elements that are either in the first set or the second set but not in both.
Example:
>>> first_set.symmetric_difference(second_set)
{1, 2, 3, 7, 8, 9}
1. add(): Adds an element to the set. If the element already exists, does nothing.
Example:
>>> s.add('f')
>>> print(s)
2. discard(): Removes an element from the set. If it does not exist, does nothing.
Example:
>>> s.discard('g')
>>> print(s)
3. remove(): Removes a specific element from the set. Raises an error if the element is not found.
Example:
>>> s.remove('e')
>>> print(s)
{'g', 'k', 's'}
Example:
>>> s.clear()
>>> print(s)
set()