Python | iter () method

Counters | File handling | Python Methods and Functions

In python, the iter () method is used for conversion to convert an iteration to an iterator. This introduces another way to iterate through the container, that is, access its elements. iter () uses

# Python3 demo code
# iter () work

 
# initializing list

lis1 = [ 1 , 2 , 3 , 4 , 5 ]

 
# print type

print ( "The list is of type: " + str ( type (lis1)))

 
# convert the list using iter ()

lis1 = iter (lis1)

  
# print type

print ( "The iterator is of type:" + str ( type (lis1)))

 
# use next () to print the iterator values ​​

print ( next (lis1))

print ( next (lis1))

print ( next (lis1))

print ( next (lis1))

print ( next (lis1))

Output:

 The list is of type: The iterator is of type: 1 2 3 4 5 

Properties of iterators

  • An iterator object stores the iteration count through the internal variable count.
  • Once the iteration is complete, it raises a StopIteration exception and the iteration counter cannot be reassigned
    to 0.
  • Therefore, it can only be used to traverse the container once.

Code # 2: Demonstration of the single bypass property

# Python 3 demo code
# iter () property

 
# initials coding list

lis1 = [ 1 , 2 , 3 , 4 , 5 ]

 
# convert the list using iter ()

lis1 = iter (lis1)

 
# prints this

print ( "Values ​​at 1st iteration:" )

for i in range ( 0 , 5 ):

print ( next (lis1))

 
# does not print this

print ( "Values ​​at 2nd iteration: " )

for i in range ( 0 , 5 ):

print   ( next (lis1))

Output:

 Values ​​at 1st iteration: 1 2 3 4 5 Values ​​at 2nd iteration: 

Exception:

 Traceback (most recent call last): File "/home/0d0e86c6115170d7cd9083bcef1f22ef.py", line 18, in print (next (lis1)) StopIteration 




Tutorials