Add/Remove Set Items
Adding and Removing Items from Sets in Python
1. Adding Items:
# Adding a single item
fruits = {'apple', 'banana', 'orange'}
fruits.add('grape')
# Now, fruits is {'apple', 'banana', 'orange', 'grape'}
# Adding multiple items
fruits = {'apple', 'banana', 'orange'}
fruits.update({'grape', 'kiwi'})
# or
fruits |= {'grape', 'kiwi'}
# Now, fruits is {'apple', 'banana', 'orange', 'grape', 'kiwi'}
2. Removing Items:
# Removing a specific item
fruits = {'apple', 'banana', 'orange'}
fruits.remove('banana')
# Now, fruits is {'apple', 'orange'}
# Removing an item without raising an error if not present
fruits = {'apple', 'banana', 'orange'}
fruits.discard('kiwi')
# Now, fruits is {'apple', 'banana', 'orange'}
# Removing an arbitrary item
fruits = {'apple', 'banana', 'orange'}
removed_item = fruits.pop()
# Now, fruits is one element less, and removed_item contains the removed element
# Clearing all items from a set
fruits = {'apple', 'banana', 'orange'}
fruits.clear()
# Now, fruits is an empty set: set()
These methods provide a way to modify the content of sets by adding or removing items. Keep in mind that sets do not allow duplicate elements, and adding an already existing element or removing a non-existing element has no effect.