TheDeveloperBlog.com

Home | Contact Us

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

Python Set remove() method with Examples

Python Set remove() 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 remove() Method

Python remove() method removes an element elem from the set. It raises error KeyError if elem is not contained in the set. See the examples given below.

Signature

remove(elem)

Parameters

elem: element to be deleted.

Return

It returns None but throws KeyError if the value does not found in the set.

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

Python Set remove() Method Example 1

Let's first see a simple example to remove an element from the set.

# Python set remove() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
# Calling method
set.remove(1)
# Displaying elements
print("After removing element: \n",set)

Output:

{1, 2, 3}
After removing element: 
 {2, 3}

Python Set remove() Method Example 2

It throws an error KeyError if the element is not available in the set. See the example.

 Python set remove() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
# Calling method
set.remove(22)
# Displaying elements
print("After removing element: \n",set)

Output:

set.remove(22)
KeyError: 22

Python Set remove() Method Example 3

This method can be easily implemented into program to perform some business logic. See an examplpe below.

# Python set remove() Method
# Creating a set
set = {'i','n','d','i','a','i','s','a','c','o','u','n','t','r','y'}
set2 = {'i','n','d','i','a','i','s','a','c','o','u','n','t','r','y'}
list = ['a','e','i','o','u']
# Displaying elements
print(set) 
for el in set:
    if el not in list:
        set2.remove(el) # Removing elements which are not in list
print(set2)

Output:

{'a', 'c', 'i', 't', 'n', 'u', 'y', 's', 'd', 'o', 'r'}
{'a', 'i', 'u', 'o'}

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