In Python, an iterator is an object representing a collection of elements (such as data or methods) where each element can be accessed by traversing through the collection to perform the required tasks.
An iterator supports the
next() function which takes no arguments and always returns the next element of the collection. When all elements are exhausted, it returns the
Objects that can be converted into iterators are called iterables. Datatypes such as lists, tuples, dictionaries, and sets are iterable, meaning that they can be converted into iterators using the
The difference between an iterable and an iterator can be easily be understood by considering iterable as a birthday cake that we need to distribute to a number of people. We cut cake into several pieces using the
iter() function to get an iterator. Then we use
next() to distribute each piece.
Also, it is important to understand that all iterators are iterable but the converse is not true.
Code for an Iterator using a List
The following code shows the generation of an iterator from a list using the
iter() function and usage of the
next() function by manually iterating through all the items of the iterator. When there are no more elements left in an iterator, it returns the
Note: Once an iterator has been iterated through, it cannot be re-iterated again.
Iterator in a
for loop has built-in
next() functions, which allows running iterations more elegantly.
Iteration using a
while loop does not have the built-in
next() functions as in the
for loop, so the
next() functions need to be used separately.
Creating a User-Defined Iterable Object
Since an iterable object is an object that can be converted into Iterator, for an object to be iterable it needs to support the
iter() function and the iterator generated must also support
In the above code, built-in
iter() function is equivalent to user-defined
__iter__() method, when
iter() function is invoked it invokes
__iter__() method after checking the data type of input argument.
next(cake_after_cutting) is same as
next() function is invoked it invokes
__next__() method after checking data type of input argument.
- Returns an iterator object for a given object.
- Anonymous contributorAnonymous contributor3077 total contributions
- Anonymous contributorAnonymous contributor1 total contribution
- Anonymous contributor
- Anonymous contributor