Python iter() Function
The Python iter() function is used to create iterator object from an iterable object. The next() method can be used to access next element of the iterator.
Syntax
iter(object, sentinel)
Parameters
object |
Required. Specify an iterable object. |
sentinel |
Optional. If the object is callable, the iteration will stop when the returned value is same as specified sentinel. |
Example: using iter() function
In the example below, an iterator called MyIter is created from a list called MyList and after that next() method is used to access next element of the iterator. Please note that, a StopIteration exception is raised when the iterator do not have more elements to iterate upon.
MyList = [10, 20, 30, 40, 50] MyIter = iter(MyList) print(next(MyIter)) print(next(MyIter)) print(next(MyIter)) print(next(MyIter)) print(next(MyIter)) print(next(MyIter))
The output of the above code will be:
10 20 30 40 50 Traceback (most recent call last): File "Main.py", line 9, in <module> print(next(MyIter)) StopIteration
Example: using iter() function with sentinel parameter
In the example below, an iterable object called MyIter is created which returns square of natural numbers. The iteration stops when the returned value becomes 81.
class square: def __init__(self): self.start = 0 def __iter__(self): return self def __next__(self): self.start += 1 return self.start**2 __call__ = __next__ MyIter = iter(square(), 81) for i in MyIter: print(i)
The output of the above code will be:
1 4 9 16 25 36 49 64
❮ Python Built-in Functions