The python iter() function is used to return an iterator object. It creates an object which can be iterated one element at a time.
Python iter() Function Syntax
It has the following syntax:
iter(object, sentinel)
Parameters
- object: An iterable object.
- sentinel (optional): It is a special value that represents the end of a sequence.
Return
It returns an iterator object.
Python iter() Function Example
The below example shows the working of the iter() function in Python.
# list of numbers
list = [1,2,3,4,5]
listIter = iter(list)
# prints '1'
print(next(listIter))
# prints '2'
print(next(listIter))
# prints '3'
print(next(listIter))
# prints '4'
print(next(listIter))
# prints '5'
print(next(listIter))
Output:
1
2
3
4
5
Explanation:
In the above example, iter() function converts an list iterable to an iterator.
Leave a Reply