Introduction to Python Iterators
Python Iterators
An iterator is an object that implements the iterator protocol, which consists of the __iter__()
and __next__()
methods.
Iterators are used to iterate over a collection of elements or to generate a sequence of values on the fly.
To create an iterator in Python, you need to define a class that implements the iterator protocol.
As an example:
my_list = [1, 2, 3, 4, 5]
# Creating an iterator using iter()
my_iter = iter(my_list)
# Iterating over the elements using next()
print(next(my_iter)) # Output: 1
print(next(my_iter)) # Output: 2
print(next(my_iter)) # Output: 3
print(next(my_iter)) # Output: 4
print(next(my_iter)) # Output: 5
In this example:
- We have a list called
my_list
containing some elements. - We create an iterator object my_iter using the
iter()
function, passing inmy_list
as the argument. - The
iter()
function converts the list into an iterator.
- We then use the
next()
function to retrieve the next element from the iterator. - Each call to next(my_iter) returns the next element in the sequence.
- In this case, we call
next()
five times to retrieve all the elements from the iterator and print them. - The output will be the elements of the list printed one by one: 1, 2, 3, 4, 5.
Iterable
An iterable is an object that can be looped over or iterated upon.
It is a more general concept and includes any object that can return an iterator. Iterables can be used directly in a for loop or passed to functions that expect iterables.
As an example:
my_list = [1, 2, 3]
for item in my_list:
print(item)
In the above example:
my_list
is an iterable that can be iterated over using a for loop.- The for loop implicitly creates an iterator from the iterable and retrieves elements one by one.
Iterator
An iterator is an object that represents a stream of data and provides a way to access the elements of the stream sequentially.
It implements the iterator protocol, which requires the object to have the __iter__()
method that returns the iterator object itself and the __next__
() method that retrieves the next element.
Iterators maintain state while iterating over the elements and can remember the position of the last accessed element.
As an example:
my_iter = iter(my_list)
print(next(my_iter)) # Output: 1
print(next(my_iter)) # Output: 2
print(next(my_iter)) # Output: 3
In this example:
my_iter
is an iterator created using theiter(
) function.- The
next()
function is used to retrieve elements from the iterator sequentially.