Iterator | How To Build A Basic Iterator?

In this post, we will learn How to build a basic iterator in Python which we can perform using two of the given functions are __iter__ and __next__ which is explained here in detail.

 Iterator

Iterator

As we know that it is an object which could be iterated upon and here we have given an example for it and understand the concept clearly along with the implementation.

class MyIterat:
    def __init__( self, max_value):
        self.current_value = 0
        self.max_value = max_value
    
    def __iter__( self):
        return self
    
    def __next__( self):
        if self. current_ value < self.max_value:
            result = self.current_value
            self.current_value += 1
            return result
        else:
            raise StopIteration

In the example given here, we had defined a function named myiterat which has a parameter as the ‘max value’ of its constructor. We here defined another function as the ‘__iter__’ function to return the iterator object. And the __next__method returns the next value in the same sequence from starting and keeps on incrementing by one every time it is called till the maximum value does not reach to the maximum value.

For having a look at these of ‘myiterartor’ class go through the lines of code given below and understand the things as per our choice.

it = MyIterator(5)
for i in it:
    print( i)

As here in the example, we have given the maximum value as 5 from a list where the loop will keep on executing till it reaches the maximum values and to reach there the iterator function is executed till that time and every time here we are printing the values so the result of it will be as followed below.

0
1
2
3
4

Here we need to keep a thing in mind is we can also use the ‘next’ an inbuilt function for iterating instead of using any of the loops here so for implementing the same using next we have given the code below where we can simply get to know how we can perform the same and get it done as per our requirement and that too without using the it.

it = MyIterator(5)
print( next( it))
print( next( it))
print( next( it))
print( next( it))
print( next( it))

And here also the output will be the same.

 

 

 

To learn more about How to build a basic visit: Click hereto learn.

To learn more about the solutions to different problems and tutorials for the concepts we need to know to work on programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & Python Client To A Linux/Ubuntu Server Which Is Running C?.

Leave a Comment

%d bloggers like this: