Python Set pop() Method
Description
The pop() method removes and returns a random element from a set. If the set is empty, a KeyError exception is raised.
Syntax
Syntax of the pop() method:
set.pop()
Parameters
- None
Return Value
Returns the removed element.
Example
Randomly remove an element:
Example 1
fruits
= {
"
apple
"
,
"
banana
"
,
"
cherry
"
}
fruits
.
pop
(
)
(
fruits
)
The output is:
{'apple', 'banana'}
Output the return value:
Example 1
fruits
= {
"
apple
"
,
"
banana
"
,
"
cherry
"
}
x
=
fruits
.
pop
(
)
(
x
)
The output is:
banana
Notes
- Elements in a set are unordered, so each time the
pop()method is called, the removed element is random. - If you need to remove a specific element, you should use the
remove()ordiscard()method instead ofpop()。
Python Sets