Middle
What is an iterator and a generator, what methods should they implement, and what is the difference?
sobes.tech AI
Answer from AI
Iterator — an object that allows sequential traversal of collection elements. In Python, an iterator must implement the following methods:
__iter__()— returns the iterator itself;__next__()— returns the next element or raisesStopIterationif there are no more elements.
Generator — a special type of iterator created using functions with the yield keyword or generator expressions. Generators automatically implement iterator methods.
Differences:
- An iterator can be implemented manually, while a generator is easier to create using
yield. - Generators are lazy and save memory, as elements are created on demand.
Example of a generator:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)