12. Python pop()

发布时间:2023-12-08

Python pop()

更新:2022-07-24 13:04 Python 中的pop()函数有助于从集合中移除任意元素。它还将移除的元素作为输出返回。

set.pop()

pop()参数:

pop()函数不接受任何参数。它通过移除返回元素来更新集合。

pop()返回值

这个函数的返回值是集合中的一个随机元素。如果集合为空,此函数将引发类型错误异常。

投入 返回值
如果设置 随机元素

Python 中pop()方法的示例

示例 Python 集中pop()的工作方式?

X ={1, 2, 3, 4}
print('Return Value is', X.pop())
print('X = ', X)

输出:

Return Value is 4
A =  {1, 2, 3}

示例pop()如何处理空集合?

# 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