The purpose of this content is to explore Iterator in Python along with examples. First things first, this tutorial will look at what an iterator is.
What is an Iterator?
An iterator is an object that is used to iterate or loop through the elements or items in the collections such as List, Set, etc.
Iterator: the name came from iterating which is a technical term for looping the elements.
What is an Iterator in Python?
An iterator is an object which is meant for the purpose in Python, is nothing but looping through iterable objects like lists, tuples, dicts, and sets.
Instantiating the Iterator in Python
The iterator consists of two methods:
- iter() and
Iter() method is used to initialize the iterator object so that the instance of this object can be used for iterating.
myiterator = iter()
Iteration of the Iterator
The next() method is used to iterate over the iterable objects. The next() method returns the next value in the iterable object.
item = next(myiterator)
Iterator vs Iterable
In Python, the List, Tuple, Set, and Dict are all iterable objects. These iterable objects have an iter() method which is used to get an iterator. It also considered the string object an iterable object in Python.
tupleObj = (“Red”, “Orange”)
myiterator = iter(tupleObj)
Here, you will look at how to return an iterator from the list and display the value using print().
Here, you will look at how to return an iterator from the String object and display each value with print().
Ok, and with that, you looked into what an Iterator is and what an Iterable Object is. Now, let us move on to loops.
Loop Through an Iterator on a Collection Object
Loop can be used to iterate through iterable objects.
In this example, you will see how to iterate over the list in Python. You will see 2 methods to iterate over a list in Python.
Method 1: Using for loop
Method 2: Using for loop and range()
In this example, you will look at how to iterate over the tuple in Python. Here, you will be using for loop to iterate through tuple.
In this example, you will see how to iterate over the String in Python. You are going to use for loop in this example to iterate through String.
Built-in Iterators in Python
There are some compelling built-in Iterators in Python, which will be very useful for the programmers for effective looping, and it also speeds up the code execution.
These built-in iterators are available in the module ‘itertools’ in Python. This module implements several iterative building blocks.
Here are a few useful iterators in Python
This accumulate iterator will take two parameters. These two parameters are nothing but an iterable target and function, which will be followed at each iteration of value in target.
If the input iterable is empty, then the output iterable also will be empty. If no function is passed, addition takes place by default.
Chain (iter1, iter2…):
Chain iterator function is used to print all the values in iterable one after another mentioned in the function parameters.
Create an Iterator
In Python, you can create a class/object as an iterator. In order to create as an iterator, you must implement the methods __iter__() and __next__().
To initialize the class/object in python, _init_() can be used.
The above-mentioned _iter_() method acts similar to _init_() but always returns the iterator object itself.
_next_() method also allows operations and must return the next item in the order.
-- Operation --
-- Operation --
In this example, you will create an iterator that returns odd numbers starting from 1.
self.a = 1
x = self.a
self.a += 2
myclass = randomNumbers ()
print(‘Iterator in python’)
print((‘Iterator in python’)
print((‘Iterator in python’)
Here, the randomNumbers is an object/class which is being implemented with two methods _iter_() and _next_() for an iterator.
Now, execute this program to see the output.
In this example, you will create an iterator that returns the iteration between the start and stop numbers.
def __init__(self, start, stop):
self.num = start
self.stop = stop
if self.num > self.stop:
self.num += 1
return self.num - 1
# Driver code
if __name__ == '__main__' :
a, b = 2, 5
pizzaCtr1 = PizzaCounter(a, b)
pizzaCtr2 = PizzaCounter(a, b)
# Method 1-to print the range without iter()
print ("Display the range without iter()")
for iter1 in pizzaCtr1:
print ("Eating Pizzas, couter ", iter1, end ="\n")
print ("\n Display the range using iter()\n")
# Method 2- using iter()
obj = iter(pizzaCtr2)
print ("Eating Pizzas, couter ", next(obj))
print ("\n Done Pizzas, GAME OVER")
Let us execute the above program and see the output.
StopIteration in Python
StopIteration is a statement that will be useful when you want to stop the iteration at state to prevent the iteration from going over and over.
If you don’t use a StopIteration statement, then the iteration will go forever in a for loop or if you have enough next() methods.
The StopIteration can be used in the next() method to prevent the iteration after a specific condition or termination statement.
-- Operation --
-- Operation –
Let us see an example program and see the output.
In this example, you must create an iterator in Python to iterate up to 10 counters. When the iteration reaches 10, you should raise StopIteration to prevent further iteration.
Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer
An iterator is a basic object that can be iterated over in Python. A data-returning object that returns data in one-at-a-time increments. An iterator is a set of countable values. Iterators are objects that can be iterated over, which means you can go through all of the values. A Python object that implements the iterator protocol, which includes the methods __iter__() and __next__, is known as an iterator ().
Iterators have the advantage of being energy efficient. You don’t have to memorize the entire number system to get all the odd numbers. You can have infinite objects in finite memory.
To learn more about iterators in Python, join Simplilearn’s Data Science with Python Certification Course. The Python Data Science course will show you how to learn Python programming concepts. You can gain expertise in data mining, machine learning, data visualization, web crawling, and natural language processing as a result of this Python for Data Science Training. You will master the basic tools of Data Science with Python after completing this course.
This course includes 68 hours of blended learning, four business-based assignments, interactive learning with Jupyter notebooks laboratories, lifelong self-paced learning, and dedicated mentoring sessions from industry experts.
If you have any questions for us, leave them in the comments section of this tutorial. Our experts will get back to you on the same, at the earliest. Happy learning!