Iterators in Python with Examples

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

class MyIter:
    def __init__(self):
        self.n=1
        self.x=50
    def __iter__(self):
          return self        
    def __next__(self):
      if(self.n<=50):  
          m=self.n
          self.n=self.n+1
          return m
      else:
          raise StopIteration
    
    def __previous__(self):
      if(self.x>=0):  
          m=self.x
          self.x=self.x-1
          return m
      else:
          raise StopIteration 

data=MyIter()
# for i in data:
#     print(i)
        
print(data.__previous__())
print(data.__previous__())
print(data.__previous__())












# mylist=[10,20,30,40,50]
# myit=iter(mylist)
# #print(myit)
# for i in mylist:
#     print(myit.__next__())

# # print(myit.__next__())
# # print(myit.__next__())
# # print(myit.__next__())
# # print(myit.__next__())

 

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *