Iterator in Python: A simple Introduction

string = 'Medium'
iter_obj = iter(string)
print(next(iter_obj))          # M
print(iter_obj.__next__()) # e
print(iter_obj.__next__()) # d
print(next(iter_obj)) # i
print(next(iter_obj)) # u
print(next(iter_obj)) # m
print(next(iter_obj))     # raise a StopIteration exception
File “02_iterator.py”, line 39, in <module>
print(next(iter_obj)) # raise a StopIteration exception
StopIteration
class SquareAll:# contructor
def __init__(self, max=0):
self.current = 1
self.max = max
def __iter__(self):
return self

def __next__(self):
if self.current <= self.max:
sqr_val = self.current * self.current
self.current += 1
return sqr_val
else:
raise StopIteration
sqr_obj = SquareAll(max=5)
print(next(sqr_obj_iterator))     # 1
print(next(sqr_obj_iterator)) # 4
print(next(sqr_obj_iterator)) # 9
print(next(sqr_obj_iterator)) # 16
print(next(sqr_obj_iterator)) # 25
print(next(sqr_obj_iterator)) # raise a StopIterator expection
sqr_obj = SquareAll(max=5)    # iterablefor item in sqr_obj:
print(item) # print 1 4 9 16 25
iterator_object = iter(some_iterable_object)while True:
try:
item = next(iterator_object)
except StopIteration:
break

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store