Python iter() method
python iter() method returns the iterator object, it is used to convert an iterable to the iterator.
Syntax : iter(obj, sentinel)
Parameters :
- obj : Object which has to be converted to iterable ( usually an iterator ).
- sentinel : value used to represent end of sequence.
Returns : Iterator object
Properties of Iterators
- Iteration object remembers iteration count via internal count variable.
- Once the iteration is complete, it raises a StopIteration exception and the iteration count cannot be reassigned to 0.
- Therefore, it can be used to traverse the container just once.
Python iter() Example
Example 1: Python iterate list
Python3
# Python3 code to demonstrate# working of iter()# initializing listlis1 = [1, 2, 3, 4, 5]# printing typeprint("The list is of type : " + str(type(lis1)))# converting list using iter()lis1 = iter(lis1)# printing typeprint("The iterator is of type : " + str(type(lis1)))# using next() to print iterator valuesprint(next(lis1))print(next(lis1))print(next(lis1))print(next(lis1))print(next(lis1)) |
Output
The list is of type : <class 'list'> The iterator is of type : <class 'list_iterator'> 1 2 3 4 5
Example 2: Python iterate list with index
Python3
# Python 3 code to demonstrate# property of iter()# initializing listlis1 = [1, 2, 3, 4, 5]# converting list using iter()lis1 = iter(lis1)# prints thisprint("Values at 1st iteration : ")for i in range(0, 5): print(next(lis1))# doesn't print thisprint("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


Please Login to comment...