Iterators in Python Explained
Everything you need to know about Iterators

Everything in Python is an object and so goes an iterator. An iterator is a Python object which can be looped over one element at a time. Some of the objects in Python which can be classified as iterator include:
- Lists
- String
- dictionaries
- tuples
- sets
What is Iterating
Iteration is the process of looping over an iterable object. Consider the example below of a list which contains some of the most popular social media platforsm
socials = ["WhatsApp", "Youtube", "Tiktok", "Instagram", "Twitter","Snapchat"]
We can loop over each elememt in the lits and display it as follows:
socials = ["WhatsApp", "Youtube", "Tiktok", "Instagram", "Twitter","Snapchat"] for social in socials: print(social)
The output will be:
WhatsApp
Youtube
Tiktok
Instagram
Twitter
Snapchat
How Iteration Works
Whenever you write a for loop or when you are iterating, the python object is first conveertrd in to an iterator object. All iterable objects have the iter() function which allows us to iterate over the iterate object. Then the next() function is called on each iteration.To get the iterator object from our social list, we will do this:
social_iterator_object = iter(socials)print(social_iterator_object)
The output will be:
<list_iterator object at 0x7f17f0d0a250>
next() function
The next function is responsible for fetching the next item when we are iterating. Lets print out the whole operation.
Here we print out each element using the next function and the output will be:
WhatsApp
Youtube
Tiktok
Instagram
Twitter
Snapchat
What if we pritnt out the element at an index which does not exist: Add the following code.
index6= next(social_iterator_object)print(index6)
The out put will be:
Traceback (most recent call last):
File "itera.py", line 19, in <module>
index6= next(social_iterator_object)
StopIteration
Conclusion
In this tutorial, you have learned how to create iterators and manually iterate over an iterator using the next()
function.