Python Set remove() method
Python Set remove() method
The set.remove() method in Python removes the specified element from the set if it is present in the set else this method will raise an error if the specified item does not exist.
Syntax
set.remove(element)
Parameter
element- This parameter signifies the item to search for and later to remove it.
Return
This method returns the specified element from the set.
Example 1
# Python program explaining # the set.remove() method #initializing set1 set1 = {"mango", "banana", "apple", "tomato"} print("Actual Set 1:",set1) # removing "banana" item from the set value= set1.remove("banana") # printing the removed value print("Element removed from set:",value) # printing the set after pop method print("After the removing the value...\nNew Set: ", set1)
Output
Actual Set 1: {'mango', 'tomato', 'banana', 'apple'} Element removed from set: None After the removing the value New Set: {'mango', 'tomato', 'apple'}
Example 2
# Python program explaining # the set.remove() method #initializing set1 set1 = {1, 2,3,4,5,6,7} print("Actual Set 1:",set1) # removing "banana" item from the set value= set1.remove() # passing no element # will pass an TypeError as remove() takes one argument print("Element removed from set:",value) # printing the set after pop method print("After the removing the value...\nNew Set: ", set1)
Output
Actual Set 1: {1, 2, 3, 4, 5, 6, 7} Traceback (most recent call last): File "main.py", line 8, in <module> value= set1.remove() # passing no element TypeError: remove() takes exactly one argument (0 given)
Example 3
# Python program explaining # the set.remove() method # initializing vowel set vowel = {'a', 'e', 'i', 'o', 'u'} # Deleting 'z' element vowel.remove('z') # the element 'z' is not present in the sent # Updated vowel set # will return a KeyError as the element 'z' is not present print('Updated vowel set: ', vowel)
Output
Traceback (most recent call last): File "main.py", line 8, in <module> vowel.remove('z') # the element 'z' is not present in the sent KeyError: 'z'