Familiarity with the Iterator Concept in Python

python iterators introduction
10 November 2024

Hello! Today we want to discuss the concept of Iterator in the programming language Python. This discussion allows you to effectively work with data structures like lists, dictionaries, and similar cases. But before diving into the details, it's better to first know what an Iterator is and what functionality it provides.

In Python, an Iterator is a feature that allows you to traverse through all the items present in a data collection, without needing to keep the entire collection simultaneously in memory. This topic, especially when dealing with large data, can be very resource-efficient. For example, if you want to apply an algorithm on a large list of data, using an Iterator can significantly help manage memory efficiently.

In fact, when using a construct like for or while that requires traversing through a sequence, an Iterator is employed. Therefore, if possible, you should directly work with it; however, it's conceivable to encounter situations where how it works might be unclear.

Basically, what makes an Iterator unique? Every object that has the method __iter__() and a method __next__() that is used to retrieve the next item in the sequence can be recognized as an Iterator. When you reach the end of the sequence and there are no more items to return, an exception named StopIteration is raised.

Next, we want to look at some sample code that demonstrates how to use an Iterator in Python. Please take a look at the code below, and then I'll explain it line by line.

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
if self.a <= 5:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)

Code Explanation

class MyNumbers:
Defines a class named MyNumbers
def __iter__(self):
Defines the method __iter__() that is often used for initializing the primary variables. self.a = 1 assigns the initial value to a and return self returns the Iterator itself.
def __next__(self):
The method __next__() retrieves the current value of a and then increments the value of a by one. If a exceeds 5, it raises a StopIteration exception.
myclass = MyNumbers()
Creates an instance of the MyNumbers class
myiter = iter(myclass)
Retrieves an Iterator from the class using the built-in iter() function
for x in myiter:
Uses the for loop to traverse through each item in the Iterator and prints the values

FAQ

?

What functionality does an Iterator have in Python?

?

How can I create an Iterator?

?

Can an Iterator be infinite?