Python Tutorial for Beginners
Removing Elements From Python Set
Using remove() or discard() method
The built-in remove()
method in Python can be used to delete elements from the set. However, if the element doesn't exist in the set, a KeyError is thrown.
Use discard()
to delete entries from a set without causing a KeyError; if the element does not exist in the set, it will stay unaffected.
Using pop() method
The Pop()
method can also be used to remove and return one element from a set. However, it only removes the set's final element.
Note that if the set is unordered, the pop()
method has no means of determining which element gets popped.
discard()
method
Using clear() method
For removal of all the elements from a set, you can make use of the clear() method.
Loop Items
You can use the for loop in order to loop through the items in a set.
Example:
this_set = {"yellow", "red", "green"}
for x in this_set:
print(x)
Output:
yellow
red
green