TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Python Set discard() method with Examples

Python Set discard() method with Examples on python set add() method, python set discard() method, python set pop() method, python set remove() method, python tutorial, introduction, applications etc.

<< Back to PYTHON

Python Set discard() Method

Python discard() method discards or remove the elememt from the set. This method does not return anything, even no error if the elememt is not present. It takes a parameter which is an elememt to be removed. The method signature is given below.

Signature

discard(elem)

Parameters

elem: element to be deleted.

Return

It returns None.

Let's see some examples of discard() method to understand it's functionality.

Python Set discard() Method Example 1

A simple example to use discard method to remove an element.

# Python set discard() Method
# Creating a set
set = {1,2,3,4,5}
# Displaying elements
print(set) 
# Calling function
set.discard(2)
print(set)

Output:

{1, 2, 3, 4, 5}
{1, 3, 4, 5}

Python Set discard() Method Example 2

If the element is not present it returns none to the caller method.

# Python set discard() Method
# Creating a set
set = {1,2,3,4,5}
# Displaying elements
print(set) 
# Calling function
val = set.discard(22)
print(val)

Output:

{1, 2, 3, 4, 5}
None

Python Set discard() Method Example 3

An example where we are implementing this method into a program. It removes all odds elements.

# Python set discard() Method
# Creating a set
set = {1,2,3,4,5}
set2 = {1,2,3,4,5}
# Displaying elements
print(set) 
# Calling function
for s in set2:
    if s%2!=0:
        set.discard(s)  # Discard all odd elements
print(set)

Output:

{1, 2, 3, 4, 5}
{2, 4}

Next TopicPython Set




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf