Python Iterators
In Python, an iterator is an object that implements the iterator protocol, which consists of the methods __iter__()
and __next__()
. The iterator protocol allows an object to be iterated (looped) over, and it provides a way to retrieve the next value in a sequence.
Basic Iterator Example:
class MyIterator:
def __iter__(self):
self.start = 1
return self
def __next__(self):
if self.start <= 5:
result = self.start
self.start += 1
return result
else:
raise StopIteration
# Using the iterator
my_iterator = MyIterator()
for value in my_iterator:
print(value)
In this example, the MyIterator
class implements the iterator protocol. The __iter__
method initializes the iterator, and the __next__
method provides the next value in the sequence. The iteration stops when the StopIteration
exception is raised.
Iterable Objects:
An iterable is an object that can be iterated over. An iterable should implement the __iter__
method, which returns an iterator object.
class MyIterable:
def __init__(self):
self.start = 1
def __iter__(self):
return self
def __next__(self):
if self.start <= 5:
result = self.start
self.start += 1
return result
else:
raise StopIteration
# Using the iterable
my_iterable = MyIterable()
for value in my_iterable:
print(value)
In this example, MyIterable
is an iterable class that returns an iterator object when the __iter__
method is called.
Using iter()
and next()
Functions:
The iter()
function is used to get an iterator from an iterable, and the next()
function is used to retrieve the next value from an iterator.
my_iterable = MyIterable()
my_iterator = iter(my_iterable)
print(next(my_iterator)) # Output: 1
print(next(my_iterator)) # Output: 2
print(next(my_iterator)) # Output: 3
Using Generators:
Generators are a concise way to create iterators in Python. A generator function uses the yield
keyword to produce a sequence of values.
def my_generator():
start = 1
while start <= 5:
yield start
start += 1
# Using the generator
gen = my_generator()
for value in gen:
print(value)
Generators automatically implement the iterator protocol, and they are a convenient way to create iterators without explicitly implementing the __iter__
and __next__
methods.
Iterators and iterables are fundamental concepts in Python, and they are extensively used in loops and other constructs that involve iterating over a sequence of values.