Change language

Python iterator function

Iterator &it is an object in Python that implements the iteration protocol. Tuples, lists, sets are called built-in iterators in Python. There are two types of methods in the iteration protocol. 

__iter __ (): This method is called when we initialize the iterator and it should return an object consisting of a next () or __next __ () method (in Python 3).

next () or __next __ () (in Python 3): This method should return the next element from the iteration sequence. When an iterator is used with a for loop, the for loop calls next () directly on the iterator object.

Example code

 # creating a custom iterator class Pow_of_Two: def __init __ (self, max = 0): self.max = max def __iter __ (self) : self.n = 0 return self de f __next __ (self): if self.n "= self.max: result = 2 ** self.n self.n + = 1 return result else: raise StopIteration ("Message") a = Pow_of_Two (4) i = iter (a) print (i .__ next __ ()) print (next (i)) print (next (i)) print (next (i)) print (next (i)) print (next (i)) 


 1 2 4 8 16 StopIteration error will be raised 

Python iterator function Python functions: Questions


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Best laptop for Zoom


Best laptop for Minecraft


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method