What is an iterator in Python?
💡 Model Answer
An iterator is an object that implements the iterator protocol, which consists of the methods __iter__() and __next__(). The __iter__() method returns the iterator object itself, and __next__() returns the next value from the underlying collection. When the data is exhausted, __next__() raises StopIteration. Iterators allow you to traverse containers lazily, consuming memory only as needed. Example: for x in [1, 2, 3]: print(x) internally creates an iterator over the list and repeatedly calls __next__() to get each element. Complexity is O(n) for iterating over n items, with O(1) additional space.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500