Iterators in Python
An iterator is an object that contains a countable number of values and can be traversed one value at a time.
➡️ Iterators use
__iter__() and __next__().Iterator Example
numbers = [1, 2, 3]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))
Using for Loop with Iterator
numbers = [10, 20, 30]
for num in numbers:
print(num)
StopIteration Error
❌ Raised when iterator has no more items.
Practice
- Create an iterator from a list
- Access elements using next()