Iterators in Python (60/100 Days of Python)
Iterators are a fundamental part of the Python programming language, allowing you to process elements of a sequence one at a time. In this tutorial, we will cover the basics of iterators in Python and how to use them effectively in your code.
What are Iterators?
An iterator is an object that represents a sequence of values. It allows you to loop through a collection of items and access each item in turn, without having to know the underlying implementation of the sequence. In Python, an iterator is an object that implements two methods: __iter__()
and __next__()
.
The __iter__()
method returns the iterator object itself, and the __next__()
method returns the next value in the sequence. When there are no more items in the sequence, __next__()
raises the StopIteration
exception to signal the end of the iteration.
Creating an Iterator
In Python, you can create an iterator by implementing the __iter__()
and __next__()
methods in a custom class:
class MyIterator:
def __init__(self, data):
self.index = 0
self.data = data
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
result = self.data[self.index]
self.index += 1
return result
In this example, we create an iterator called MyIterator
that takes a list of data as input. The __init__()
method initializes the index and data attributes, while the __iter__()
method returns the iterator object itself. The __next__()
method retrieves the next value in the sequence and updates the index counter. When there are no more values to retrieve, it raises the StopIteration
exception.
Using an Iterator
Once you have created an iterator object, you can use it to loop through a sequence of values:
my_list = [1, 2, 3, 4, 5]
my_iterator = MyIterator(my_list)
for value in my_iterator:
print(value)
In this example, we create a list called my_list
and an iterator object called my_iterator
that takes my_list
as input. We then loop through the values in my_iterator
using a for
loop and print each value to the console.
Built-in Iterators in Python
Python also provides several built-in iterators that you can use in your code. Here are a few examples:
range()
The range()
function returns an iterator that generates a sequence of numbers from a starting value to an ending value. Here's an example:
for i in range(5):
print(i)
This code generates the sequence of numbers 0 to 4 and prints each number to the console.
enumerate()
The enumerate()
function returns an iterator that generates pairs of indices and values from a sequence:
my_list = ['apple', 'banana', 'orange']
for i, value in enumerate(my_list):
print(i, value)
This code generates pairs of indices and values from the my_list
sequence and prints them to the console.
zip()
The zip()
function returns an iterator that generates tuples of corresponding elements from one or more sequences:
my_list1 = [1, 2, 3]
my_list2 = ['apple', 'banana', 'orange']
for value1, value2 in zip(my_list1, my_list2):
print(value1, value2)
This code generates pairs of corresponding elements from my_list1
and my_list2
and prints them to the console.
Iterators are especially useful when processing a large dataset. This comes in handy for applications in Data Science and Machine Learning.
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course
- Full series: 100 Days of Python
- Previous topic: Custom Exceptions in Python
- Next topic: Generators