Google News
logo
Python Program to Remove an item in a set
In the following example of Python program to remove an item from a set :
Program :
# create a set
my_set = {1, 2, 3, 4, 5}

# remove an item from the set
my_set.remove(3)

# print the updated set
print(my_set)
Output :
{1, 2, 4, 5}
This program creates a set `my_set` with the values `{1, 2, 3, 4, 5}`. Then, it removes the value `3` from the set using the `remove()` method.

Finally, it prints the updated set, which will be `{1, 2, 4, 5}`. Note that if the specified item is not found in the set, the `remove()` method will raise a `KeyError` exception.

To avoid this, you can use the `discard()` method instead, which will remove the item if it exists, but won't raise an exception if it doesn't.