The iter()
function is used to create an iterator that iterates through the elements of an iterable object.
iter(iterable, sentinel[optional])
copy
iterable |
The iterable object to iterate over. |
sentinel |
An optional value which when encountered, the StopIteration exception will be raised. |
The required iterable
argument represents the object that is to be iterated over. It can be any iterable object such as a list, tuple, string, or custom object that implements the iteration protocol.
The optional sentinel
parameter is used to specify a sentinel value that, when returned by the iterator's __next__()
method, will indicate the end of iteration.
iter with callable objects
When the iter()
function is called with a callable object that implements the iterator protocol, it creates an iterator using that object. The iterator is responsible for generating values by repeatedly calling the __next__()
method of the callable object until a specific condition is met (such as reaching the end of a sequence or encountering a sentinel value).