Python set discard method explanation with an example

Published by admin on

python set discard

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 :

set.discard(e)

 

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 :

#1
setA = set()

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

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

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

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

#5
setA.discard(element)
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}
Categories: python

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *