discard() set function in python by R4R Team

- discard() is a python in-built function which is applicable only for the set data type
- it is used for remove the specified item from the set.
- Work of both remove() and discard() are same but the major difference between them is that remove give an error if item is not in the list but discard not give an error.

Syntax-

set.discard(item)

Example

set is {1,2,3}
then set.discard(2) will give {1,3}


program-

set1=set([1,2,3,4,5,"one","two","three"])
print("Set is ",set1)

set1.discard(2)
print("Set is",set1)

set1.discard("one")
print("Set is",set1)

set1.discard(3)
print("Set is",set1)

set1.discard("three")
print("Set is",set1)


output-

Set is {1, 2, 3, 4, 5, 'three', 'one', 'two'}
Set is {1, 3, 4, 5, 'three', 'one', 'two'}
Set is {1, 3, 4, 5, 'three', 'two'}
Set is {1, 4, 5, 'three', 'two'}
Set is {1, 4, 5, 'two'}


-In this program, we have a set {1,2,3,4,5,"one","two","three"} then we discard items 2,3,"one","three" and print the set one by one.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!