Junior
What is the difference between an iterator and a generator in Python?
sobes.tech AI
Answer from AI
An iterator is an object that implements the iteration protocol (iter() and next()). It allows sequential traversal of a collection's elements. A generator is a special type of iterator created using a generator function (contains the keyword yield). Generators generate values "on the fly," saving memory.
Key differences:
- Implementation: An iterator implements the iteration protocol with classes. A generator is implemented with a function containing
yield. - Memory: Generators are more memory-efficient as they generate values on demand without storing the entire sequence in memory at once. Iterators can store the entire collection.
- Single use: Generators can be used for iteration only once. An iterator, if it is not a generator, can be iterated multiple times if recreated.
# Example of an iterator
class MyIterator:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < self.limit:
self.current += 1
return self.current
else:
raise StopIteration
# Example of a generator
def my_generator(limit):
for i in range(1, limit + 1):
yield i