Remove Items From Set In Python

Python Set Definition

A set is an unordered collection data type with no duplicate elements. Sets are iterable and mutable. The elements appear in an arbitrary order when sets are iterated.

The elements of the set can not be duplicate. The elements of the python set must be immutable.


Removing elements from a set

There are a number of ways to remove items from a set:

  • Use the remove() method if you want to remove a single element from a set, or get an error message if the respective item is not in the set.
  • Use the discard() method if you want to remove a single element from a set but don’t need an error message if the given item is not in the set.
  • Use the pop() method to remove and return a random element from a set.
  • Use the clear() method to remove all items from a set.

Example:



Output:

 Printing the element using for loop...
 Rakesh
 Pankaj
 Anmol
 Mukesh
 Sujeet
 Rahul

In above example, remove() method is used to remove the element Prayag.


Example: using discard() method




Outpu:

 Printing the element using for loop...
 Rahul
 Anmol
 Prayag
 Mukesh
 Pankaj
 Sujeet

In above example, discard() method is used to discard the element Rakesh.


Example: pop() method




Outpu:

 Rahul
 {'Aimtocode', 'Anmol', 'Prayag'}

You can also use the pop(), method to remove an item, but this method will remove the last item.