Let us say, we have a Set that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to remove 'Kriti' from the Set.
It can be done with the 'remove( )' and 'discard( )' Function.
There is a mild difference between 'remove( )' and 'discard( )' Function. Let us see them below.
At first let us look at the 'remove( )' Function.
x = {"Mohan", "Kriti", "Salim"} x.remove("Kriti") print(x)
So, in the above code we have created a 'Set' and initialised to the variable 'x'.
Next, we have used the 'remove( )' Function that searches for the name 'Kriti' and removes it from the Set.
And we get the below output,
Now, if we replace 'remove( )' with 'discard( )' Function. It will also behave exactly as the 'remove( )' Function.
x = {"Mohan", "Kriti", "Salim"} x.discard("Kriti") print(x)
The only difference between 'remove( )' and 'discard( )' Function is, if the element to be removed is not present in the Set, the 'remove( )' Function will raise an error. Whereas 'discard( )' Function will not raise an error.
x = {"Mohan", "Kriti", "Salim"} x.remove("George") print(x)
So, we are trying to remove 'George' that is not present in the Set.
And the 'remove( )' Function throws an error.
The 'pop( )' Function can be used to remove an item from the Set. But it does not remove the last element.
As there is no indexing, the 'pop( )' Function could remove any element.
x = {"Mohan", "Kriti", "Salim"} x.pop() print(x)
So, in the above code we have created a 'Set' and initialised to the variable 'x'.
Below is how the values are positioned in the Set,
Next, we have used the 'pop( )' function that can remove any element from the Set.
In this case 'Mohan' is removed from the Set.
And we get the below output,
The 'clear( )' Function can be used to remove all the elements from the Set.
x = {"Mohan", "Kriti", "Salim"} x.clear() print(x)
So, in the above code we have created a 'Set' and initialised to the variable 'x'.
Next, we have used the 'clear( )' function that removes all the elements from the Set making the Set empty.
And we get an empty Set as output,
The output 'set( )' means, it represents an empty Set.
We have seen, the 'clear( )' Function can be used to remove all the elements from the Set.
Now, let us see, how can we delete a Set completely.
The 'del' keyword is used to remove the Set completely.
x = {"Mohan", "Kriti", "Salim"} del x print(x)
So, in the above code we have created a 'Set' and initialised to the variable 'x'.
Next, we have used the 'del' keyword to delete the Set completely.
And when we try printing the Set,
It ends up with an error.
As the set 'x' no longer exist.