iter(object)

iter(object, sentinel)

Returns an iterator object.

Parameters

The iter() function accepts two parameters:

  • obj - can be a list, set, tuple, etc. A collection object that supports iteration (implements __iter__()), or an object that supports the sequence protocol (implements __getitem__(), where the argument is an integer starting from zero). If another object is passed, a TypeError is raised.
  • sentinel optional — If this argument is provided, obj must be a callable object. In this case, the created iterator will call the specified object (without arguments) with each call to its next() and check the returned value for equality with sentinel. If the returned value equals sentinel, StopIteration is raised; otherwise, the returned value is returned. The function returns an iterator over the object that supports iteration over its elements.

Return Value

The iter() function returns:

  • an iterator object for the given argument until the sentinel is found
  • TypeError for a user-defined object that does not implement __iter__() and __next__() or __getitem__()

Examples

One use of sentinel is reading lines until a desired one is reached. The following example reads a file until the readline() method returns an empty string:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        pass  # Do something with line.

User-defined type defining __call__():

class MyIterable:

    def __init__(self):
        self.index = 0
        self.items = [1, 2, 3, 4]

    def __call__(self):
        value = self.items[self.index]
        self.index += 1
        return value

iterator = iter(MyIterable(), 3)

print(next(iterator))  # 1
print(next(iterator))  # 2
print(next(iterator))  # StopIteration