Iterator
一句话解释
iterator 是 对象 那个 produces 值 one at 时间 using __next__(), 启用 lazy evaluation 的 序列.
用大白话说
iterator 是对象那个 represents stream 的数据 — 它 produces 值 one at 时间 on demand. 你获取下一个值 使用 next(), and iterator raises StopIteration when exhausted.
Lists, strings, dicts, and files are iterable (you can loop over them), but they are not iterators themselves. You create an iterator from an iterable with iter(). The for loop does this automatically.
Iterators are lazy — they don't compute all values upfront. This makes them memory-efficient for large or infinite sequences. Generators are a convenient way to create iterators using yield.
示例
nums = [1, 2, 3]
it = iter(nums)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3
# next(it) would raise StopIteration
# for loop uses iter() internally
for n in nums:
print(n)Iterators produce 值 one at 时间 使用 下一个(). iter() 创建 iterator 从 iterable.
常见混淆
容易混淆的对象: iterable
关键区别: iterable 是 任何 对象 你 能 循环 over (列表, 字符串, dict) — 它 有 __iter__. iterator 是 对象 那个 actually produces 值 one at 时间 — 它 有 __next__. 每个 iterator 是 iterable, 但 不 每个 iterable 是 iterator.
相关术语
相关资源
相关课程
- Iterators
Iterators in Python.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。