Python: Remove All Elements from Set using Clear()/Difference_Update()/Discard()

Python set is a list of items that are not ordered. – Each element in the set must be unique and immutable, and duplicate elements are removed from the sets. Sets are mutable, which means they can be changed after they have been created.

The elements of the set, unlike other Python sets, do not have an index, which means we cannot access any element of the set directly using the index. To get the list of elements, we can either print them all at once or loop through the collection.

Examples:

Input:

givenset= {'this', 'is', 'BTechGeeks'}

Output:

set()

Delete all the elements from the set

There are several ways to remove all the elements from the set some of them are:

Method #1:Using discard() function

In Python, the built-in method discard() removes an element from a collection only if it is already present. If the element is missing from the list, no error or exception is thrown, and the original set is printed.

Approach:

  • While iterating over a set, we cannot modify it.
  • So We will make a list of the set’s elements, then iterate through that list, removing each element from the set.

Below is the implementation:

# given set
givenset = {'this', 'is', 'BTechGeeks'}

# using for loop to traverse the set
for element in list(givenset):
    # remove that element from set
    givenset.discard(element)
# print the set
print(givenset)

Output:

set()

Method #2:Using clear() function

The clear() method clears the set of all elements.

syntax:

given_set.clear()

parameters:

The clear() method accepts no parameters.

Return :

The clear() method does not return a value.

Below is the implementation:

# given set
givenset = {'this', 'is', 'BTechGeeks'}

# using clear()
givenset.clear()
# print the set
print(givenset)

Output:

set()

Method #3:Using difference_update() method

The Set class in Python has a function called difference update() that takes a sequence as an argument and removes all of the elements from the set. let us use this method to remove all the elements from the set

We can pass given set as parameter for the difference_update() function

Below is the implementation:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# using difference_update()
givenset.difference_update(givenset)
# print the set
print(givenset)

Output:

set()

Related Programs:

Leave a Comment