Python set discard method explanation with an example

Introduction :

In this tutorial, we will learn about the discard method of python set. The discard method is used to remove a specific element from a set if it is available. The syntax of  the discard method is as below :


This method takes one parameter. It will check this parameter if it is available in the set or not. If it is available, it will remove it from the set.

It returns None i.e. it doesn’t return anything.

Example :

setA = set()

lengthA = int(input("Enter the total elements for the set : "))

for i in range(lengthA):
    e = int(input("Enter value {} : ".format(i + 1)))

print("setA before discard : {}".format(setA))

element = int(input("Enter the element to discard : "))

print("setA after discard : {}".format(setA))

Explanation :

The commented numbers in the above program denote the step numbers below :

  1. Create one empty set setA.
  2. Ask the user to enter the total element of the set. Read it and store it in lengthA variable.
  3. Using a for loop, read the values for the set and add them one by one.
  4. Print the setA to the user.
  5. Ask the user to enter the element to discard. Store the value in the element variable. Discard the element using the discard method. Print the set again after the discard is completed.

python set discard

This program is also available on [Github]( _

Sample Output :

Enter the total elements for the set : 4
Enter value 1 : 1
Enter value 2 : 2
Enter value 3 : 3
Enter value 4 : 4
setA before discard : {1, 2, 3, 4}
Enter the element to discard : 4
setA after discard : {1, 2, 3}

Similar tutorials :