An iterator is an object in Python that enables you to traverse through all the elements of a collection, one element at a time. It implements two special methods: __iter__()
and __next__()
. The iter()
function returns an iterator from an iterable, and next()
retrieves the next item.
numbers = [1, 2, 3]
it = iter(numbers)
print(next(it)) # Output: 1
print(next(it)) # Output: 2
# 1. Using iter() and next()
fruits = ["apple", "banana", "cherry"]
fruit_iter = iter(fruits)
print(next(fruit_iter)) # Output: apple
print(next(fruit_iter)) # Output: banana
# 2. Iterating using a for loop (internally uses iter and next)
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
# 3. Custom iterator class
class CountDown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
num = self.current
self.current -= 1
return num
cd = CountDown(3)
for num in cd:
print(num)
# Output: 3 2 1
# 4. Handling StopIteration
nums = [10, 20]
it = iter(nums)
print(next(it)) # Output: 10
print(next(it)) # Output: 20
# print(next(it)) # Raises StopIteration
# 5. Checking if object is an iterator
from collections.abc import Iterator
print(isinstance(it, Iterator)) # True
print(isinstance(nums, Iterator)) # False
print(isinstance(iter(nums), Iterator)) # True