Python iter() Function Examples
Let us see a few examples of the iter function in Python.
Python Iterate List using iter Function
In this example, we will take a Python List and use the iter() method on it and convert it into an iterator.
Python3
# Python3 code to demonstrate # working of iter() # initializing list lis1 = [ 1 , 2 , 3 , 4 , 5 ] # printing type print ( "The list is of type : " + str ( type (lis1))) # converting list using iter() lis1 = iter (lis1) # printing type print ( "The iterator is of type : " + str ( type (lis1))) # using next() to print iterator values print ( next (lis1)) print ( next (lis1)) print ( next (lis1)) print ( next (lis1)) print ( next (lis1)) |
The list is of type : <class 'list'> The iterator is of type : <class 'list_iterator'> 1 2 3 4 5
Python Iterate List with Index
In this example, we will take a Python List and use the iter() function on it. Then convert it into an iterator and print its value using the next() function.
In the second iteration, we again try to print the values using the next() function. But this time it generated an error because in the first iteration, the iterator has already reached its limit and there are no more values in it to print.
Python3
# Python 3 code to demonstrate # property of iter() # initializing list lis1 = [ 1 , 2 , 3 , 4 , 5 ] # converting list using iter() lis1 = iter (lis1) # prints this print ( "Values at 1st iteration : " ) for i in range ( 0 , 5 ): print ( next (lis1)) # doesn't print this print ( "Values at 2nd iteration : " ) for i in range ( 0 , 5 ): print ( next (lis1)) |
Expected Output:
Values at 1st iteration :
1
2
3
4
5
Values at 2nd iteration :
Actual Exception (Error):
Traceback (most recent call last):
File "/home/0d0e86c6115170d7cd9083bcef1f22ef.py", line 18, in
print (next(lis1))
StopIteration
Python iter() method
python iter() method returns the iterator object, it is used to convert an iterable to the iterator.