Python __iter__() and __next__() - Converting an Object into an Iterator

We frequently need to access an object, such as an iterator. Creating a generator loop is one method, but it takes more time and effort on the part of the coder. Python makes this work easier by including a built-in function called __iter__(). We will learn about Python's __iter__() and __next__() in this post.

Python __iter__()

Python's __iter__() method yields an iterator for the supplied object, which can be an array, set, tuple, or custom object. __next__() in Python builds an object that can be accessed one element at a time, which is useful when working with loops.

Syntax

  • Object: The object for which an iterator has to be constructed. It may be a user-defined object (OOPS) or a collection object such as a list or tuple.
  • Callable, Sentinel: Sentinel value indicates the end of the sequence being iterated, and callable represents a callable object. Sentinel value also indicates the value at which the iteration must cease.

Exception

Python's __iter__() function yields an iterator object that traverses each member of the supplied object. In Python, __next__() provides access to the next element. Iteration continues until the value is located or the end of the elements is reached in the case of the callable object and sentinel value. Regardless, there is no alteration to the original item.

In this example, we are iterating through the list and printing the next member on the following line by using the iter and next function.

Program Explanation:

This Python code demonstrates how to use the next() method to loop over a list's members and the iter() function to build an iterator. The following describes each section of the code:

  • initialises a list of vowels using the formula listA = ['a', 'e', 'i', 'o', 'u'].
  • iter_listA = iter(listA): Uses the iter() function to create an iterator from the list.
  • Potential exceptions are handled via the try block.
  • Within the attempt block:

next(iter_listA): To obtain the subsequent element from the iterator, call the next() method.

To recover each vowel in order, this is done more than once.

  • The StopIteration exception, which arises when the iterator has no more elements, is caught by the unless block.

This code shows how to retrieve entries from the iterator in a sequential manner up until the end of the list when a StopIteration exception is triggered. This exception is handled by the except block, which enables error-free code execution.

Output:

a
e
i
o
u

Python __next__()

The next element of the iteration is returned by the Python function __next__(). The StopIteration exception is raised if there are no more items. It is a feature of the iterable and iterator interface. It lets us design unique iterable objects, like generators, and manage the process of extracting each element from those iterables one at a time.

In this example, we're using Python's __next__() method to loop through the list and output the next entry.

Program Explanation:

This little Python code illustrates how to generate an iterator from a list and iterate through its members using a while loop, as well as how to use the iter() function and the __next__() method. Using iter_lst.__next__(), the try block tries to get the next element from the iterator; if it is successful, it outputs the element. The unless block exits the loop when a StopIteration exception is triggered, which keeps the loop going. This sample demonstrates how to manually iterate through a list's elements using the iter() method and the iterator interface.

Output:

111
222
333
444
555

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

Program Explanation:

The supplied Python snippet shows how to use the iterator methods on a list and the iter() function in basic terms. It uses the __iter__() function to obtain an iterator (iter_listB) and initializes a list called a list with strings. Subsequent elements are subsequently retrieved from the iterator by repeatedly calling the __next__() function. Try-except blocks are used to catch StopIteration errors, though, which occur when an attempt is made to access more elements than are contained in the list. Upon reaching the end of the list, the program publishes each element till handling the exception and generates a message announcing the end of the iteration along with a note about the 'StopIterationError.'

Output:

Rat
Hat
Fat
Bat
Throwing 'StopIterationError,' I cannot count more.

User-defined objects (using OOPS)

In this example, we demonstrate the usage of iter() utilizing OOPS in Python by implementing the __iter__() and __next__() procedures using user-defined objects.

Program Explanation:

The provided Python code creates a Counter class that, for a given range of numbers, implements a basic iterator. The two arguments that the class accepts are start and end, which stand for the range's inclusive start and end values. The iterator object (itself) is returned by the __iter__ method, while the counter is initialized with the supplied values by the __init__ method. When the end of the range is reached, the __next__ method raises a StopIteration exception and generates the next value in the range.

The driver code creates two instances of the Counter class, c1, and c2, with the same start and finish values. The first part of the code demonstrates how to traverse across the range using a for loop on the object (c1). Another technique for manually iterating throughout the range using a while loop that makes use of the iter() and next() methods is shown in the second section (c2). The software produces a customized message indicating that the game has terminated due to overindulgence in pizza when the range is achieved. Additionally, it produces notifications that indicate how many pizzas are being consumed.

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 more Pizzas, counting  2
Eating more Pizzas, counting  3
Eating more Pizzas, counting  4
Eating more Pizzas, counting  5

Dead on overfood, GAME OVER

Next TopicPython 3 basics