- Mastering Python Scripting for System Administrators
- Ganesh Sanjiv Naik
- 116字
- 2021-07-02 14:00:28
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
推薦閱讀
- 自制編譯器
- Arduino by Example
- 跟老齊學Python:輕松入門
- Instant 960 Grid System
- Getting Started with Python Data Analysis
- Cocos2d-x學習筆記:完全掌握Lua API與游戲項目開發 (未來書庫)
- Unity Game Development Scripting
- Linux:Embedded Development
- C#程序設計教程(第3版)
- Solutions Architect's Handbook
- jQuery for Designers Beginner's Guide Second Edition
- Python Digital Forensics Cookbook
- 官方 Scratch 3.0 編程趣味卡:讓孩子們愛上編程(全彩)
- AngularJS UI Development
- Visual C++程序設計全程指南