In this lesson, we will focus on removing the items in a Python Set. We will see Python Set Remove methods with different coding examples. Before this, let’s learn all the methods used for this purpose.
There are different Python Methods to remove an item in a set. These python methods are given below:
Beside these methods, there are also another method and a function that do this job. But they delete all the items. So what are these method and function. They are given below:
You can also check Python Set Add Method
Clear method deletes all the items in a python set.
Del function deletes the complete python set.
To learn these methods better, let’s give coding example for each of them.
You can Watch the video of this lesson!
You can also check Python Set Difference Method
The first method used to remove a python set item is remove method. With this method, we can remove a specific item in a python set. We can give the item that we sould like to remove as an item. There can be only one item for remove method.
In the below example, we will remove “Balin” from the set.
The output of this python code will be:
Again, the below example will remove
The output of this python code will be like below:
Like remove method, discard method is also used fort he same purpose. The usage of this method is also similar to remove method.
The below exmaple is also a number set example for discard method usage.
The last method that is used as python set remove method and remove one item of a python set is pop method. But pop method is a little risky. Because it removes the last item in the set. But we do not know the last member of any set, it is random. So, when we use python pop method with a set, we remove any item randomly.
Let’s check the below example. When we run the below example;
Everytime we run the code, the output will change and remove one of the items randomly.
Python set clear method is used to remove all the items in a set. With this method, we do not use any parameters and when we use this method with a set, all the items in the set is removed.
This methos is also sued in list to remove all the list items. But there is no such method for tuples.
Del function is the function which deletes the complete set. After this command there is nothing about previously defined set.
After the above python code, we will receive an error as output that says there is no such item (dwarves1).
In this lesson, we have learned three different methods that works as python set remove method. We have also learned another method named clear method, that deletes all the items in the set. Beside, we have seen del function, that deletes the complete set. You can check the other methods of sets in this Python Programming Course.
Leave a Reply