Python next() 内置函数

来自 Python 3 文档

通过调用其 __next__() 方法检索迭代器的下一个项。如果提供了 default,则在迭代器耗尽时返回它,否则引发 StopIteration。

简介

next() 函数从迭代器中检索下一个项。如果迭代器耗尽,它会引发 StopIteration 异常。

您也可以提供一个默认值,在迭代器耗尽时返回该值,从而避免 StopIteration 异常。

示例

使用 next() 和迭代器:

my_list = [1, 2]
my_iter = iter(my_list)

print(next(my_iter))
print(next(my_iter))

try:
    print(next(my_iter))
except StopIteration:
    print("Iterator is exhausted")
1
2
Iterator is exhausted

使用 next() 和默认值:

my_iter = iter([1])
print(next(my_iter, "default"))
print(next(my_iter, "default"))
1
default

更多示例:

i = iter([1, 2, 3])
print(next(i))
print(next(i))
print(next(i))
1
2
3

相关链接