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()



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Properties of Iterators

  • 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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.