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, aTypeErroris raised.sentineloptional — If this argument is provided,objmust be a callable object. In this case, the created iterator will call the specified object (without arguments) with each call to itsnext()and check the returned value for equality withsentinel. If the returned value equalssentinel,StopIterationis 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
TypeErrorfor 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