In this article, we are going to learn all about the python iter() function to return an iterator object.
Here we will understand the python built-in iter() function to create an iterator object and access all the items of an iterable using iterator object.
Table of Contents
Python iter function
Python iter function is a built-in function in python that is used to returns an iterator object.
Syntax
The syntax of the python iter() function is:-
iter(object, sentinel)
Parameter
iter function in python accepts two parameters.
- object:– Required, an iterable object.
- sentinel:- Optional, If the object is callable object The iteration will stop when the return value same as the sentinel.
Return Value
The return value of the Python iter()
function is the iterator object.
Python iter example
Here we will understand the iter function along with an example.
my_list = ['Python', 'Java', 'C++', 'C', 'PHP']
#create iterator object
my_iterator = iter(my_list)
#Access all the items of my_list using my_iterator object and next() function.
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
Output
Output:
Python
Java
C++
C
PHP
Conclusion
In this article, you have learned all about the Python iter() function to create the iterator object.
An iterator is an object in python that can be iterated upon, meaning an iterator object contains a countable number of values.
You can access all the items of iterable passing the iterator object in the next() function.
If this article helps you, please comment and keep visiting for further python built-in functions tutorials.
Python built-in functions
For more information:- Click Here