Python | Remove () and Discard () in sets

Python Methods and Functions

Examples:

 Input: set = ([10, 20, 26, 41, 54, 20]) Output: {41, 10, 26, 54} Input: set = (["ram "," aakash "," kaushik "," anand "," prashant "]) Output: {' ram', 'prashant',' kaushik', 'anand'} 

Method 1: Using the discard () method

Python's built-in discard () method removes an element from a set only if that element is present in the set. If the item is not in the set, then no errors or exceptions are thrown and the original set is printed. 
If an element is present in the set:

# Python program to remove random selection items
# Function to remove elements using discard ()

def Remove (sets):

sets.discard ( 20 )

print (sets)

 
Driver code

sets = set ([ 10 , 20 , 26 , 41 , 54 , 20 ])

Remove (sets)

Output:

 {41, 10, 26, 54} 

If element is missing from the set :

# Python program to remove random selection items
# Function to remove items using discard ()

def Remove (sets):

sets.discard ( 21 )

p rint (sets)

 
Driver code

sets = set ([ 10 , 20 , 26 , 41 , 54 , 20 ])

Remove (sets)

Output:

 {41, 10, 26, 20, 54} 

Method 2: Using the remove () method

The built-in remove () method in Python removes an item from a set only if if the element is present in the set, the same as the discard () method, but if and the item is not in the set, an error is thrown, or an exception is raised. 
If an element is present in the set:

# Python program to remove random selection items
# Function to remove elements using remove ()

def Remove (sets):

sets.remove ( "aakash" )

print (sets)

 
Driver code

sets = set ([ "ram" , " aakash " , "kaushik" , "anand" , "prashant" ])

Remove (sets)

Output:

 {'ram',' anand', 'prashant',' kaushik'} 

If the item is not in the set:

# Python program to remove random selection items
# Function to remove items using remove ()

def Remove (sets):

sets.remove ( "gaurav" )

print (sets)

 
Driver code

sets = set ([ " ram " , "aakash" , "kaushik" , "anand" , "prashant" ])

Remove (sets)

Output:

 No Output 

Error:

 Traceback (most recent call last): File "/home/bf95b32da22ada77d72062a73d3e0980.py", line 9, in Remove (sets) File "/home/bf95b32da22ada77d72062a73d3e0980.py", line 4, in Remove sets.remove ("gaurav") KeyError '




Tutorials