Add/Remove Set Items
Add/Remove Set Items
Add items to set:
If you want to add a single item to the set use the add() method.
Example:
Output:
If you want to add more than one item, simply create another set or any other iterable object(list, tuple, dictionary), and use the update() method to add it into the existing set.
Example:
Output:
Remove items from set:
We can use remove() and discard() methods to remove items form list.
Example 1:
Output:
Example 2:
Output:
The main difference between remove and discard is that, if we try to delete an item which is not present in set, then remove() raises an error, whereas discard() does not raise any error.
Example 1:
Output:
Example 2:
Output:
There are various other methods to remove items from the set: pop(), del(), clear().
pop():
This method removes the last item of the set but the catch is that we don’t know which item gets popped as sets are unordered. However, you can access the popped item if you assign the pop() method to a variable.
Example:
Output:
del:
del is not a method, rather it is a keyword which deletes the set entirely.
Example:
Output:
We get an error because our entire set has been deleted and there is no variable called cities which contains a set.
What if we don’t want to delete the entire set, we just want to delete all items within that set?
clear():
This method clears all items in the set and prints an empty set.
Example:
Output:
Check if item exists
You can also check if an item exists in the set or not.
Example 1:
Output:
Example 2:
Output: