Thursday, November 28, 2024
Google search engine
HomeLanguagesPython Set – remove() method

Python Set – remove() method

Python remove() Function is a built-in method to remove elements from the set. remove() method takes exactly one argument.

Syntax

set.remove(element)

If the element passed to the remove() is present in the set then the element will be removed from the set. If the element passed to the remove() is not present in the set then KeyError Exception will be raised. The remove() method does not return any value.

Example 1:

Python3




numbers = {1,2,3,4,5,6,7,8,9}
print(numbers)
  
# Deleting 5 from the set
numbers.remove(5)
  
# printing the resultant set
print(numbers)


Output

{1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2, 3, 4, 6, 7, 8, 9}

Example 2:

Python3




numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  
print(numbers)
  
# passing an element that is not in set
# this will throw an KeyError exception
try:
    numbers.remove(13)
except Exception as e:
    print("KeyError Exception raised")
    print(e, "is not present in the set")
  
# printing the resultant set
print("\nresultant set : ", numbers)


Output

{1, 2, 3, 4, 5, 6, 7, 8, 9}
KeyError Exception raised
13 is not present in the set

resultant set :  {1, 2, 3, 4, 5, 6, 7, 8, 9}

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments