The pop()
method removes an item from a set and returns the removed item.
Example
A = {'a', 'b', 'c', 'd'}
removed_item = A.pop()
print(removed_item)
# Output: c
pop() Syntax
The syntax of the pop()
method is:
set.pop()
Here, pop()
removes an item from the set and updates it.
pop() Parameters
The pop()
method doesn't take any parameters.
pop() Return Value
The pop()
method returns:
- a removed item from the set
TypeError
exception if the set is empty
Example 1: Python Set pop()
A = {'10', 'Ten', '100', 'Hundred'}
# removes random item of set A
print('Pop() removes:', A.pop())
# updates A to new set without the popped item
print('Updated set A:', A)
Output
Pop() removes: 10 Updated set A: {'Ten', '100', 'Hundred'}
In the above example, we have used pop()
to remove the item of set A. Here, pop()
removes 10 from set A and returns it.
Also, set A is updated to the new set without the removed item 10.
Note: We may get a different output every time we run it, because pop()
returns and removes a random element.
Example 2: pop() with an Empty Set
# empty set
A ={}
# throws an error
print(A.pop())
Output
TypeError: pop expected at least 1 argument, got 0
In the above example, we have used pop()
with an empty set A. The method can not remove any item from an empty set so it throws an error.
Also Read: