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

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

主站蜘蛛池模板: 台湾省| 长子县| 南安市| 谢通门县| 东台市| 朝阳县| 会泽县| 木里| 井陉县| 东山县| 吉林市| 师宗县| 大连市| 清徐县| 英德市| 东丽区| 瑞昌市| 云南省| 紫金县| 玛沁县| 鄄城县| 左权县| 阜南县| 临朐县| 重庆市| 论坛| 宜春市| 正阳县| 始兴县| 双桥区| 梁平县| 芦山县| 宁远县| 夹江县| 宾川县| 徐闻县| 灵丘县| 大港区| 开江县| 瑞金市| 怀仁县|