xxxxxxxxxx
my_set = {1, 2, 3, 4, 5}
element_to_remove = 3
my_set.remove(element_to_remove)
print(my_set)
xxxxxxxxxx
s = {0, 1, 2}
s.discard(0)
print(s)
{1, 2}
# discard() does not throw an exception if element not found
s.discard(0)
# remove() will throw
s.remove(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
xxxxxxxxxx
# it doesn't raise error if element doesn't exits in set
thisset = {1, 2,3}
thisset.discard(3)
print(thisset)
xxxxxxxxxx
nameSet = {"John", "Jane", "Doe"}
nameSet.discard("John")
print(nameSet)
# {'Doe', 'Jane'}
xxxxxxxxxx
some_set = { 1, 2, 3 }
# Unsafe method = Throws exception if element does not exist in the set
some_set.remove(4) # Throws exception since 4 does not exist in some_set
# Safe method = Does not matter whether the element is in the set or not
some_set.discard(4) # No exception
xxxxxxxxxx
mySet = {1, 2, 3}
mySet.remove(1)
print(mySet)
# Output:
# {2, 3}
xxxxxxxxxx
my_set = {1, 2, 3, 4, 5} # Example set
my_set.remove(3) # Using remove()
print(my_set) # Output: {1, 2, 4, 5}
my_set.discard(5) # Using discard()
print(my_set) # Output: {1, 2, 4}
xxxxxxxxxx
nameSet = {"John", "Jane", "Doe"}
nameSet.remove("Jane")
print(nameSet)
# {'John', 'Doe'}