官术网_书友最值得收藏!

Iterators

In Python, an iterator is an object that can be iterated upon. It is an object that will return data, one element at a time. Python's iterator object implements two methods, __iter__() and __next__(). Mostly, iterators are implemented within loops, generators, and comprehensions.

In the following example, we are using the next() function, which will iterate through all of the items. After reaching the end and there is no more data to be returned, it will raise StopIteration, as shown in the following example:

numbers = [10, 20, 30, 40]

numbers_iter = iter(numbers)

print(next(numbers_iter))
print(next(numbers_iter))
print(numbers_iter.__next__())
print(numbers_iter.__next__())

next(numbers_iter)

Output:
10
20
30
40
Traceback (most recent call last):
File "sample.py", line 10, in <module>
next(numbers_iter)
StopIteration

主站蜘蛛池模板: 马边| 监利县| 蒙自县| 大关县| 探索| 景东| 乐山市| 房产| 犍为县| 石门县| 岳西县| 沙河市| 饶河县| 玉溪市| 玉山县| 三河市| 武隆县| 桦甸市| 洛宁县| 凭祥市| 云龙县| 肥东县| 松滋市| 汝州市| 东台市| 长海县| 寿阳县| 乌苏市| 木兰县| 上虞市| 股票| 吉水县| 浑源县| 渑池县| 靖宇县| 屏山县| 井陉县| 兴文县| 肥东县| 云阳县| 凤城市|