Change language

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

| |

Function iter (object) iter (callable, sentinel)

Exception :

 If we call the iterator after all the elements have been iterated, then  StopIterationError  is raised. 

The __iter __ () function returns an iterator object that iterates through each element of the given object. The next element can be accessed through the __next __ () function. In the case of a callable and a clock item value, iteration is performed until a value is found or the end of items is reached. In any case, the original object does not change.

Code # 1:

# 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"  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 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

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

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically