Sets let you store unique items. Adding and removing elements helps you change what is in the set easily.
Adding and removing set elements in Python
my_set.add(element) my_set.remove(element) my_set.discard(element) my_set.pop()
add() adds an element to the set.
remove() deletes an element but causes an error if the element is not found.
discard() deletes an element but does not cause an error if the element is missing.
pop() removes and returns an arbitrary element from the set.
fruits = {'apple', 'banana'}
fruits.add('orange')fruits.remove('banana')fruits.discard('grape')item = fruits.pop()
This program shows how to add and remove elements from a set. It adds 'bird', removes 'cat', tries to discard 'fish' safely, and pops an element.
my_set = {'cat', 'dog'}
print('Original set:', my_set)
my_set.add('bird')
print('After adding bird:', my_set)
my_set.remove('cat')
print('After removing cat:', my_set)
my_set.discard('fish') # no error if not present
print('After discarding fish:', my_set)
popped = my_set.pop()
print('Popped element:', popped)
print('Set after pop:', my_set)Sets do not keep order, so elements may appear in any order when printed.
Use discard() if you want to avoid errors when removing elements that might not be in the set.
pop() removes a random element because sets are unordered.
Use add() to add elements to a set.
Use remove() to delete elements but be careful if the element might not exist.
Use discard() to delete elements safely without errors.