Python set pop() removes any random element from the set and returns the removed element. In this article, we will see about the Python set pop() method.
Example
Input: {9, 1, 0} Output: {9, 1} Explanation: By using set pop() method, a random element 0 is removed from the set and remaining set is returned.
Python Set pop() Syntax
Syntax: set_obj.pop()
Parameter: set.pop() doesn’t take any parameter.
Return: Returns the popped element from the set
Set pop() Method in Python
Python Set pop() is a method in Python used to remove and return any random element from the set. As we all know, Sets are an unordered collection of unique elements, so there’s no guarantee which element will be removed and returned by the pop() method. If the set is empty, calling pop() will raise a KeyError.
Python Set pop() Method Example
Example 1: In this example, we are using the Python Set pop() method to pop any random element from the set and then print the remaining set.
Python3
s1 = { 9 , 1 , 0 } s1.pop() print (s1) |
{9, 1}
Example 2: In this example, we are using Python Set pop() to pop 3 elements from a set and then print the remaining set.
Python3
s1 = { 1 , 2 , 3 , 4 } print ( "Before popping: " ,s1) s1.pop() s1.pop() s1.pop() print ( "After 3 elements popped, s1:" , s1) |
Before popping: {1, 2, 3, 4} After 3 elements popped, s1: {4}
Exceptions while using Python Set pop() Method
In Python, TypeError is returned if the set is empty and we try to pop out the elements from the set. In this example, pop() method is used in an empty set to pop out the element but TypeError is returned as the result.
Python3
S = {} # popping an element print (S.pop()) print ( "Updated set is" , S) |
Output:
Traceback (most recent call last):
File "/home/7c5b1d5728eb9aa0e63b1d70ee5c410e.py", line 6, in
print(S.pop())
TypeError: pop expected at least 1 arguments, got 0