Can anyone explain me the underlying logic behind the working of python ‘for’ loop ?
Well, as a backened logic we can say that python ‘for’ loops are nothing but just the combined implementation of ‘while’ loop and ‘iterator’.
For instance, consider iterating a ‘for’ loop to print values from 1 to 10 inclusive. The code for ‘for’ loop will be as follows:
for i in range(1,11): print(i)
But actually in backend this ‘for’ loop works upon a ‘while’ loop and ‘iterator’ as follows:
obj = myRange(1,10,1) temp = obj.__iter__() while(True): try: print( next(temp) ) except: break
This requires a class ‘myRange’ whose implementation can be as follows:
class myRange: def __init__(self,start,end,step): self.start = start self.end = end self.step=step def __iter__(self): //initialize your loop here. self.start = self.start-self.step return self def __next__(self): //write the main logic for iteration self.start+=self.step if self.start<=self.end: return self.start else: raise StopIteration
__init __() & __iter __() & __next __() are the inbuilt functions of the ‘iterator’.
So basically, logically the ‘for’ loop in the backened works as a combination of ‘while’ loop and ‘iterator’.
This concept is so clear and lucid to understand. Thanks for the logic behind ‘for’ loops. I greatly appreciate your solution.