Python next() 函數

Python 內置函數 Python 內置函數


描述

next() 返回迭代器的下一個專案。

語法

next 語法:

next(iterator[, default])

參數說明:

  • iterator -- 可迭代對象
  • default -- 可選,用於設置在沒有下一個元素時返回該默認值,如果不設置,又沒有下一個元素則會觸發 StopIteration 異常。

返回值

返回對象幫助資訊。

實例

以下實例展示了 next 的使用方法:

#!/usr/bin/python # -*- coding: UTF-8 -*- # 首先獲得Iterator對象: it = iter([1, 2, 3, 4, 5]) # 迴圈: while True: try: # 獲得下一個值: x = next(it) print(x) except StopIteration: # 遇到StopIteration就退出迴圈 break

輸出結果為:

1
2
3
4
5

Python 內置函數 Python 內置函數