103
Python Set pop() Method
Python pop() method pops an element from the set. It does not take any argument but returns the popped element. It raises an error if the element is not present in the set. See the examples and signature of the method is given below.
Signature
Parameters
No parameter.
Return
It returns deleted element or throws an error if the set is empty.
Let’s see some examples of pop() method to understand it’s functionality.
Python Set pop() Method Example 1
A simple example to use pop() method which removes an element and modifies the set.
Output:
{1, 2, 3, 4, 5} Element popped: 1 Remaining elements: {2, 3, 4, 5} Element popped: 2 Remaining elements: {3, 4, 5} Element popped: 3 Remaining elements: {4, 5} Element popped: 4 Remaining elements: {5}
Python Set pop() Method Example 2
If the set is empty, it throws an error KeyError to the caller function. See the example.
Output:
{1, 2} Element popped: 1 Remaining elements: {2} Element popped: 2 Remaining elements: set() Traceback (most recent call last): File "main.py", line 13, in el = set.pop() KeyError: 'pop from an empty set'
Python Set pop() Method Example 3
This example contains adding and poping elements in sequence to describe the functioning.
Output:
{1, 2} Element popped: 1 Remaining elements: {2} Element popped: 2 Remaining elements: {4} Element popped: 4 Remaining elements: {5}
Next TopicPython Set