Python | iter() method
In python, iter() method is used to convert to convert an iterable to iterator. This presents another way to iterate the container i.e access its elements. iter() uses next() for accessing values.
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
Code #1 : demonstrating iter()
# 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)) |
Output:
The list is of type : The iterator is of type : 1 2 3 4 5
- Iteration object remembers iteration count via internal count variable.
- Once the iteration is complete, it raises a StopIteration exception and iteration count cannot be
reassigned to 0. - Therefore, it can be used to traverse the container just once.
Code #2 : demonstrating property of single traversal
# 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)) |
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, inprint (next(lis1)) StopIteration
Recommended Posts:
- class method vs static method in Python
- Python | os.dup() method
- Python | set() method
- Python | next() method
- Python PIL | getbands() method
- Python | os.ftruncate() method
- Python PIL | ImagePalette() Method
- Python | os.setgroups() method
- Python PIL | GaussianBlur() method
- Python | os.truncate() method
- Python | setattr() method
- Python PIL | ImageChops.add() method
- Python PIL | Kernel() method
- Python | sympy RGS method
- Python | os.getpid() method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



