Python iter() is a built-in function that returns an iterator object.

Python iter() Function

Python iter() Syntax

iter(object,[sentinel])

Python iter() function takes two parameters as arguments.

  • object (required) – An iterable sequence whose iterator is to be created
  • sentinel (optional) – If used, the object must be callable

There are two cases of sentinel in the function.

  • When sentinel is present
    First argument i.e object is treated differently depending upon the sentinel. Object must be callable type in the presence of sentinel. The iterator created calls the object with no argument for each call to its __next__() method. This continues till the value returned is equal to the sentinel. When the value is equal to sentinel, StopIteration will be raised.
  • When sentinel is absent
    When sentinel is absent, first argument object must be a collection object that supports iteration protocol ( __iter__() function) or sequence protocol ( __getitem__() method ).
    If it doesn’t support either of these protocols in the absence of sentinel, TypeError is raised.

Python iter() Function Example

callable objects in the presence of sentinel

>>> with open(r'example.txt') as fp:
         for line in iter(fp.readline, ''):
              print line[0]

Here, the program will read the lines of file example.txt, until the sentinel character  ' ' (empty string) is encountered.

iter() function without sentinel

>>> i = iter([1,2,3,4])
>>> next(i)
1
>>> next(i)
2
>>> next(i)
3
>>> next(i)
4
>>> next(i)
Traceback (most recent call last):
 File "<pyshell#4>", line 1, in <module>
 next(i)
StopIteration