Iterators in Python
Iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration.
- __iter__(): The iter() method is called for the initialization of an iterator. This returns an iterator object
- __next__(): The next method returns the next value for the iterable. When we use a for loop to traverse any iterable object, internally it uses the iter() method to get an iterator object, which further uses the next() method to iterate over. This method raises a StopIteration to signal the end of the iteration.
Python iter() Example
G F G
Example 1: Creating and looping over an iterator using iter() and next()
Below is a simple Python custom iterator that creates an iterator type that iterates from 10 to a given limit. For example, if the limit is 15, then it prints 10 11 12 13 14 15. And if the limit is 5, then it prints nothing.
10 11 12 13 14 15
Example 2: Iterating over built-in iterables using iter() method
In the following iterations, the iteration state and iterator variable is managed internally (we can’t see it) using an iterator object to traverse over built-in iterables like list, tuple, dict etc.
List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345
Iterable vs Iterator
iterable and iterator are different. The main difference between them is, iterable cannot save the state of the iteration, but whereas in iterators the state of the current iteration gets saved.
Note: Every iterator is also an iterable, but not every iterable is an iterator in Python.
To learn more in detail about the difference between iterable and iterator, one can refer to this article: Difference between iterable and iterator.
Iterating on an Iterable
a b c d e
Iterating on an iterator
Inside loop: a b c Outside loop: d e
Getting StopIteration Error while using iterator
Iterables can be iterated over multiple times, but iterators raise StopIteration Error when all items are already iterated.
Iterable loop 1: 1,2,3,4, Iterable Loop 2: 1,2,3,4, Iterating on an iterator: 1,2,3,4, Iterator: Outside loop Traceback (most recent call last): File "scratch_1.py", line 21, in <module> print(next(iterator_obj)) StopIteration
Explanation: In the above code, we are trying to get the next element from the iterator after the completion of the for-loop. Since the iterator is already exhausted, it raises a StopIteration Exception. Whereas, using an iterable, we can iterate on multiple times using for loop or can get items using indexing.