Python iter()
is a built-in function that returns an iterator object.
iter(object,[sentinel])
Python iter()
function takes two parameters as arguments.
There are two cases of sentinel in the function.
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.__iter__()
function) or sequence protocol ( __getitem__()
method ).TypeError
is raised.>>> 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.
>>> 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