In Python, iterators and generators are tools for working with sequences of data one item at a time, which is very memory-efficient—especially for large data sets.
What is an iterator?
An iterator is an object that implements:
-
__iter__()
→ returns the iterator itself -
__next__()
→ returns the next item or raisesStopIteration
when done
nums = [1, 2, 3]
it = iter(nums)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3
print(next(it)) # Raises StopIteration
# The StopIteration exception is raised when there are no more items to iterate over.
# This is a built-in exception in Python that indicates the end of an iterator.
class CountUpTo:
def __init__(self, max):
self.max = max
self.current = 1
def __iter__(self):
return self
def __next__(self):
if self.current > self.max:
raise StopIteration
num = self.current
self.current += 1
return num
counter = CountUpTo(3)
for num in counter:
print(num)
# # This is a custom iterator that counts up to a specified maximum value.
# # The __iter__ method returns the iterator object itself, and the __next__ method
# # returns the next value in the sequence.
# # When the maximum value is reached, a StopIteration exception is raised.
# # This is a common pattern in Python for creating custom iterators.
What is GENERATORS
A generator is a simpler way to create an iterator using:
-
A function with
yield
(instead ofreturn
) -
It automatically creates an iterator object
def count_up_to(max):
current = 1
while current <= max:
yield current
current += 1
for num in count_up_to(3):
print(num)
No comments:
Post a Comment