Python Program to remove items from the set



In this article, we will learn how to remove items from the set. We will see different ways in which items can be easily removed from the set.

Let’s say we have the following input −

myset = {"bmw", "tesla", "toyota", "ford", "mercedes"}

The output should be the following after removing an item −

{'tesla', 'ford', 'bmw', 'mercedes'}

Remove items from the set using the remove() method

Using the remove() method, an error is thrown for removing an item not in the Set.

Example

# Creating a Set myset = {"bmw", "tesla", "toyota", "ford", "mercedes"} print("Set = \n",myset) # Applying the remove() method to remove an element myset.remove("toyota") # Display the updated Set print("\nSet (after removing an element) =\n",myset)

Output

Set = 
 {'mercedes', 'bmw', 'toyota', 'tesla', 'ford'}

Set (after removing an element) =
 {'mercedes', 'bmw', 'tesla', 'ford'}

Remove items from the set using the discard() method

Using the discord() method, no error is thrown for removing an item not in the Set.

Example

# Creating a Set myset = {"javascript", "php", "jquery", "angular", "react"} print("Set = \n",myset) # Applying the remove() method to remove an element myset.discard("php") # Display the updated Set print("\nSet (after removing an element) =\n",myset)

Output

Set = 
 {'javascript', 'react', 'angular', 'php', 'jquery'}

Set (after removing an element) =
 {'javascript', 'react', 'angular', 'jquery'}

Remove items from the set using the pop() method

Example

# Creating a Set myset = {"bmw", "tesla", "toyota", "ford", "mercedes"} print("Set = \n",myset) # Applying the pop() method to remove an element res = myset.pop() # Displaying the removed item print("\nRemoved item from the Set =\n",res) # Display the updated Set print("\nSet (after removing an element) =\n",myset)

Output

Set = 
 {'javascript', 'react', 'angular', 'php', 'jquery'}

Set (after removing an element) =
 {'javascript', 'react', 'angular', 'jquery'}

Advertisements