π
Iterators & Generators
Efficient looping with yield
Reward
+50 XP
Iterators
An iterator is an object with __iter__() and __next__() methods. Lists, strings, and ranges are all iterable.
nums = [1, 2, 3]
it = iter(nums)
print(next(it)) # 1
print(next(it)) # 2Generators with yield
A generator function uses yield instead of return. It produces values lazily, one at a time.
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(3):
print(x)Try it yourself
Run the example below. Edit it and see what changes.
main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)
Common mistakes
- β Calling next() past the end of an iterator raises StopIteration.
- β Generators can only be iterated once β after that they're exhausted.
