Junior — Middle
Can you explain how iterators are implemented in Python and what advantages they offer when working with data collections?
sobes.tech AI
Answer from AI
In Python, iterators are implemented through objects that implement the __iter__() and __next__() methods. An iterator allows sequential access to elements of a collection without needing to know the internal data structure.
Advantages of iterators:
- They enable working with large or even infinite sequences without loading all data into memory.
- They provide a unified interface for iterating over different types of collections.
- They simplify code by using
forloops.
Example of creating a custom iterator:
class CountUpTo:
def __init__(self, max):
self.max = max
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < self.max:
self.current += 1
return self.current
else:
raise StopIteration
for number in CountUpTo(5):
print(number)
This code will print numbers from 1 to 5, demonstrating how the iterator manages sequential access to elements.