Set Methods
1. add(x)
:
# Adds element x to the set
fruits = {'apple', 'banana', 'orange'}
fruits.add('grape')
# Now, fruits is {'apple', 'banana', 'orange', 'grape'}
2. remove(x)
:
# Removes element x from the set
fruits = {'apple', 'banana', 'orange'}
fruits.remove('banana')
# Now, fruits is {'apple', 'orange'}
3. discard(x)
:
# Removes element x from the set (if present)
fruits = {'apple', 'banana', 'orange'}
fruits.discard('kiwi') # No error raised if 'kiwi' is not in the set
# Now, fruits is {'apple', 'banana', 'orange'}
4. pop()
:
# Removes and returns an arbitrary element from the set
fruits = {'apple', 'banana', 'orange'}
removed_item = fruits.pop()
# Now, fruits is one element less, and removed_item contains the removed element
5. clear()
:
# Removes all elements from the set, leaving it empty
fruits = {'apple', 'banana', 'orange'}
fruits.clear()
# Now, fruits is an empty set: set()
6. copy()
:
# Returns a shallow copy of the set
fruits = {'apple', 'banana', 'orange'}
fruits_copy = fruits.copy()
7. union()
or |
Operator:
# Returns a new set containing all unique elements from both sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
# or
union_set = set1 | set2
8. intersection()
or &
Operator:
# Returns a new set containing common elements from both sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
# or
intersection_set = set1 & set2
9. difference()
or -
Operator:
# Returns a new set containing elements that are in the first set but not in the second set
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
# or
difference_set = set1 - set2
10. symmetric_difference()
or ^
Operator:
# Returns a new set containing elements that are unique to each set
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_diff_set = set1.symmetric_difference(set2)
# or
symmetric_diff_set = set1 ^ set2
These are just a few examples of the many set methods available in Python. Understanding and using these methods can simplify set manipulation tasks in your programs.