Python Set pop() Method
Description
The pop() method is used to remove and return a random element from the set. If the set is empty, it raises a KeyError exception.
Syntax
The syntax of the pop() method is:
set.pop()
Parameters
- None
Return Value
Returns the removed element.
Example
Randomly remove an element:
Example 1
fruits = {"apple", "banana", "cherry"}
fruits.pop()
print(fruits)
The output result is:
{'apple', 'banana'}
Output return value:
Example 1
fruits = {"apple", "banana", "cherry"}
x = fruits.pop()
print(x)
The output result is:
banana
Notes
- The elements in a set are unordered, so every 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, not thepop()。
Python Sets