  Python __iter __ () and __next __ () | Converting an Object to an Iterator

Counters | Loops | Python Methods and Functions

Function

# Python code demonstrating
# basic use of iter ()

listA = [ 'a' , 'e' , ' i' , 'o' , ' u' ]

iter_listA = iter (listA)

try :

print ( next (iter_listA))

print ( next (iter_listA))

print ( next (iter_listA))

print ( next (iter_listA))

print ( next (iter_listA))

print ( next (iter_listA)) # StopIteration error

except :

pass

Output:

aeiou

Code # 2:

 # Python code demonstrating # basic usage iter () lst = [ 11 , 22 , 33 , 44 , 55 ]    iter_lst = iter (lst) while True : try : print (iter_lst .__ next __ ())    except : break

Output:

11 22 33 44 55

Code # 3:

 # Python code demonstrating # basic use of iter ()   listB = [ 'Cat' , 'Bat' , ' Sat' , 'Mat' ]      iter_listB = listB .__ iter __ ()    try : print (iter_listB .__ next __ () ) print (iter_listB .__ next__ ()) print (iter_listB .__ next __ ()) print (iter_listB .__ next __ ()) print (iter_listB .__ next __ ()) # StopIteration error except : print ( " Throwing 'StopIterationError'" ,   " I cannot count more. " )

Exit:

Cat Bat Sat Mat Throwing 'StopIterationError' I cannot count more.

Code # 4: Custom Objects (Using OOPS)

 # Python code showing the use of iter () using OOP   class Counter : def __ init __ ( self , start, end): self . num = start self . end = end   def __ iter __ ( self ): return self     def __ next __ ( self ):    if self . num & gt;  self . end: raise StopIteration else : self . num + = 1 return self . num - 1     # Code drivers if __ name__ = = ' __main__' :   a, b = 2 , 5   c1 = Counter (a, b) c2 = Counter (a, b)   # Method 1 - print the range without iter () print ( "Print the range without iter () " )   for i in c1: print ( " Eating more Pizzas, couting " , i, end = " " )   print ( " Print the range using iter () " )   # Method 2 - using iter ()   obj = iter (c2) try :   while True : # Print before error occurs   print ( " Eating more Pizzas, couting " , next (obj)) except :  # when StopItering is raised, Print a custom message print ( "Dead on overfood, GAME OVER" )

Output:

Print the range without iter () Eating more Pizzas, couting 2 Eating more Pizzas, couting 3 Eating more Pizzas, couting 4 Eating more Pizzas, couting 5 Print the range using iter () Eating more Pizzas, couting 2 Eating more Pizzas, couting 3 Eating more Pizzas, couting 4 Eating more Pizzas, couting 5 Dead on overfood, GAME OVER