Welcome to the “Iterators & Iterables” tutorial!
Overview
- Iterable: An object you can loop over (supports
__iter__()
). - Iterator: The object returned by
iter()
(supports__next__()
).
Example
nums = [1, 2, 3]
it = iter(nums)
print(next(it)) # 1
print(next(it)) # 2
Custom Iterator
class CountDown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
for num in CountDown(3):
print(num) # 3, 2, 1
Key Takeaways
- Use
iter()
andnext()
to manually control iteration. - Implement
__iter__()
and__next__()
for custom iterators. - StopIteration signals the end of an iterator.
Happy coding!
Comments
Post a Comment