Write a Python program to remove an item from a set if it is present in the set


The program demonstrates how to remove elements from a set in Python using the discard method.

  • A set s is created using a set literal containing six elements, including duplicates. The print() function is used to display the contents of the set, which are displayed in curly braces {} and separated by commas.
  • The discard method is then used to remove specific elements from the set. The discard method takes an argument, which is the value of the element to be removed. If the element is in the set, it is removed. If the element is not in the set, the method does nothing and the set remains unchanged.
  • The discard method is used to remove the elements 20 and 50 from the set. The print() function is used to display the contents of the set after the removal of each element. The method is also used to attempt to remove the elements 5 and 15, but since these elements are not in the set, the set remains unchanged and the same contents are displayed after the removal attempt.

In this program, the discard method is used to remove specific elements from the set. If the element is in the set, it is removed, but if it is not, the method does nothing and the set remains unchanged.

Source Code

s = {30,50,70,20,30,60}
print("Original set Values : ",s)
s.discard(20)
print("Remove 0 from the said set : ",s)
s.discard(50)
print("Remove 50 from the said set : ",s)
s.discard(5)
print(s)
s.discard(15)
print(s)

Output

Original set Values :  {50, 20, 70, 60, 30}
Remove 0 from the said set :  {50, 70, 60, 30}
Remove 50 from the said set :  {70, 60, 30}
{70, 60, 30}
{70, 60, 30}