Class zrange( ) ,__iter__ method

In class zrange( ), in the iter method, why didn’t we do like this
def iter(self):
return zrange_iter(self)
because the iter method takes in an iterable as an argument and returns an iterator so why Sir wrote
def iter(self):
return zrange_iter(self.n) ???

We cannot call the __iter__ method within itself, it is recursion. zrange is a custom iterator class that we are defining. To create an iterator we need to have two methods in our class __iter__() and the __next__(). When iter method is called on any iterable or iterator, it should return the iterator itself. That is why inside the __iter__ method we should return self. self refers to the object itself which is an iterator. While in the next method it should return the next element in the stream of data. You should also raise a StopIteration exception when the data stream has ended.

You can define your custom range function like this:

class myrange:    

    def __init__(self, *args):
        if len(args) == 1:
            self.start = -1
            self.stop = args[0]
            self.step = 1
        elif len(args) == 2:
            self.start = args[0]-1
            self.stop = args[1]
            self.step = 1
        elif len(args) == 3:
            self.start = args[0]-args[2]
            self.stop = args[1]
            self.step = args[2]
        print(self.start, self.stop, self.step)
            
    def __iter__(self):
        return self
    
    def __next__(self):
        self.start += self.step
        if self.start >= self.stop:
            raise StopIteration
        return self.start   

for i in myrange(12, 22, 2):
    print(i, end=" ")

I hope this helped. :slight_smile:

HI @rishavraj1808_a240d978fe1ee795 hope your doubt has been resolved …for now I closing this doubt if you still have any isuue please do contact

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.