Open In App

Python __iter__() and __next__() | Converting an object into an iterator

Last Updated : 28 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In many instances, we get a need to access an object like an iterator. One way is to form a generator loop but that extends the task and time taken by the programmer. Python eases this task by providing a built-in method __iter__() for this task. In this article, we will see about Python __iter__() and __next__().

Python __iter__()

The __iter__() function in Python returns an iterator for the given object (array, set, tuple, etc., or custom objects). It creates an object that can be accessed one element at a time using __next__() in Python, which generally comes in handy when dealing with loops.

Syntax

iter(object)
iter(callable, sentinel)
  • Object: The object whose iterator has to be created. It can be a collection object like a list or tuple or a user-defined object (using OOPS).
  • Callable, Sentinel: Callable represents a callable object, and sentinel is the value at which the iteration is needed to be terminated, sentinel value represents the end of the sequence being iterated.

Exception

If we call the iterator after all the elements have 
been iterated, then StopIterationError is raised.

The __iter__() in Python returns an iterator object that goes through each element of the given object. The next element can be accessed through __next__() in Python. In the case of the callable object and sentinel value, the iteration is done until the value is found or the end of elements is reached. In any case, the original object is not modified.

In this example, we are using the iter and next function to iterate through the list and print the next element in the next line.

Python3




# Python code demonstrating
# basic use of iter()
listA = ['a','e','i','o','u']
 
iter_listA = iter(listA)
 
try:
    print( next(iter_listA))
    print( next(iter_listA))
    print( next(iter_listA))
    print( next(iter_listA))
    print( next(iter_listA))
    print( next(iter_listA)) #StopIteration error
except:
    pass


Output

a
e
i
o
u

Python __next__()

Python __next__() is responsible for returning the next element of the iteration. If there are no more elements then it raises the StopIteration exception. It is part of the iterable and iterator interface, which allows us to create custom iterable objects, such as generators, and control how elements are retrieved one at a time from those iterables.

In this example, we are using __next__() function in Python to iterate and print next element inside the list.

Python3




# Python code demonstrating
# basic use of iter()
lst = [11, 22, 33, 44, 55]
 
iter_lst = iter(lst)
while True:
    try:
        print(iter_lst.__next__())
    except:
        break


Output

11
22
33
44
55

In this example, we are using __next__() in Python to show the exception that is thrown if next element is not present.

Python3




# Python code demonstrating
# basic use of iter()
 
listB = ['Cat', 'Bat', 'Sat', 'Mat']
 
 
iter_listB = listB.__iter__()
 
try:
    print(iter_listB.__next__())
    print(iter_listB.__next__())
    print(iter_listB.__next__())
    print(iter_listB.__next__())
    print(iter_listB.__next__())
except:
    print(" \nThrowing 'StopIterationError'",
                     "I cannot count more.")


Output

Cat
Bat
Sat
Mat
 
Throwing 'StopIterationError' I cannot count more.

User-defined objects (using OOPS) 

In this example, we are using user defined objects along with defining __iter__() and __next__() functions to show the use of iter() using OOPS in Python.

Python3




class Counter:
    def __init__(self, start, end):
        self.num = start
        self.end = end
 
    def __iter__(self):
        return self
 
    def __next__(self):
        if self.num > self.end:
            raise StopIteration
        else:
            self.num += 1
            return self.num - 1
                        
# Driver code
if __name__ == '__main__' :
    a, b = 2, 5
    c1 = Counter(a, b)
    c2 = Counter(a, b)
     
    # Way 1-to print the range without iter()
    print ("Print the range without iter()")
     
    for i in c1:
        print ("Eating more Pizzas, counting ", i, end ="\n")
     
    print ("\nPrint the range using iter()\n")
     
    # Way 2- using iter()
    obj = iter(c2)
    try:
        while True: # Print till error raised
            print ("Eating more Pizzas, counting ", next(obj))
    except:
        # when StopIteration raised, Print custom message
        print ("\nDead on overfood, GAME OVER")


Output

Print the range without iter()
Eating more Pizzas, counting  2
Eating more Pizzas, counting  3
Eating more Pizzas, counting  4
Eating more Pizzas, counting  5

Print the range using iter()

Eating mor...


Previous Article
Next Article

Similar Reads

Converting WhatsApp chat data into a Word Cloud using Python
Let us see how to create a word cloud using a WhatsApp chat file. Convert the WhatsApp chat file from .txt format to .csv file. This can be done using Pandas. Create a DataFrame which read the .txt file. The .txt file had no columns like it is in an .csv file. Then, split the data into columns by separating them and giving each column a name. The f
4 min read
Converting string into DateTime in Python
Working with dates and times is a common task in programming, and Python offers a powerful datetime module to handle date and time-related operations. In this article, we are going to convert the string of the format 'yyyy-mm-dd' (yyyy-mm-dd stands for year-month-day) into a DateTime object using Python. Example: Input: '2023-07-25' Output: 2023-07
3 min read
Converting Matrix into Row Echelon Form in Python
In this article, we will see how we can convert the matrix into a Row Echelon Form. We will see how we can do this with the help of a Python Program for converting the matrix to Row Echelon Form. What is the Row Echelon Form?A matrix is in Row Echelon form if it has the following properties: Any row consisting entirely of zeros occurs at the bottom
5 min read
Converting A Blob Into A Bytearray In Python Flask
In web development, dealing with binary data, such as images or files, is a common requirement. Blobs (Binary Large Objects) are a representation of binary data, and at times, you may need to convert a blob into a more manageable data structure, like a Python bytearray. This article will guide you through the process of converting a blob into a byt
2 min read
Converting Row into list RDD in PySpark
In this article, we are going to convert Row into a list RDD in Pyspark. Creating RDD from Row for demonstration: C/C++ Code # import Row and SparkSession from pyspark.sql import SparkSession, Row # create sparksession spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate() # create student data with Row function data = [Row(name=
1 min read
Converting Pandas Crosstab into Stacked DataFrame
In this article, we will discuss how to convert a pandas crosstab to a stacked dataframe. A stacked DataFrame is a multi-level index with one or more new inner levels as compared to the original DataFrame. If the columns have a single level, then the result is a series object. The panda's crosstab function is a frequency table that shows the relati
4 min read
Converting Jinja Comments into Documentation
Developers often face the challenge of creating comprehensive documentation for their code. However, by leveraging Jinja, a powerful template engine for Python, it becomes possible to automatically generate documentation from code comments. This article will explore the process of using Jinja to extract information from code comments and create str
5 min read
Python | Difference between iterable and iterator
Iterable is an object, that one can iterate over. It generates an Iterator when passed to iter() method. An iterator is an object, which is used to iterate over an iterable object using the __next__() method. Iterators have the __next__() method, which returns the next item of the object. Note: Every iterator is also an iterable, but not every iter
3 min read
Python | range() does not return an iterator
range() : Python range function generates a list of numbers which are generally used in many situation for iteration as in for loop or in many other cases. In python range objects are not iterators. range is a class of a list of immutable objects. The iteration behavior of range is similar to iteration behavior of list in list and range we can not
2 min read
Python PIL | ImageSequence.Iterator()
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageSequence module contains a wrapper class that lets you iterate over the frames of an image sequence. ImageSequence.Iterator() This class implements an iterator object that can be used to loop over an image sequence. You can use the [ ]
1 min read
Practice Tags :