Python 中的 pop() 函数用于从集合中移除任意元素。它还会将移除的元素作为其输出返回。
set.pop()
pop() 函数不带任何参数。它通过移除返回的元素来更新集合。
此函数的返回值是集合中的一个随机元素。如果集合为空,此函数会引发 TypeError 异常。
| 输入 | 返回值 |
|---|---|
| 如果集合 | 随机元素 |
X ={1, 2, 3, 4}
print('Return Value is', X.pop())
print('X = ', X)
输出
Return Value is 4
A = {1, 2, 3}
# on an empty set
X = {}
# Popping elements and printing them
print(X.pop())
# The updated set
print("Updated set is", X)
输出
Traceback (most recent call last):
File "/home/7c5b1d5728eb9aa0e63b1d70ee5c410e.py", line 6, in
print(X.pop())
TypeError: pop expected at least 1 arguments, got 0