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
- next().
Iter() method is used to initialize the iterator object so that the instance of this object can be used for iterating.
Syntax is
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.
Syntax is
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.
Syntax is
tupleObj = (“Red”, “Orange”)
myiterator = iter(tupleObj)
print(next(myiterator))
Example 1
Here, you will look at how to return an iterator from the list and display the value using print().
Output
Example 2:
Here, you will look at how to return an iterator from the String object and display each value with print().
Output
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.
Example 1:
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
Output
Method 2: Using for loop and range()
Output
Example 2:
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.
Output
Example 3:
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.
Output
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
accumulate(iter, func):
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.
Output
Chain (iter1, iter2…):
Chain iterator function is used to print all the values in iterable one after another mentioned in the function parameters.
Output
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.
Syntax
Class className:
def __iter__(self):
-- Operation --
return self
def __next__(self):
-- Operation --
return x
Example 1
In this example, you will create an iterator that returns odd numbers starting from 1.
class randomNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 2
return x
myclass = randomNumbers ()
myiterator= iter(myclass)
print(‘Iterator in python’)
print(next(myiterator))
print((‘Iterator in python’)
print(next(myiterator))
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.
Output
Example 2:
In this example, you will create an iterator that returns the iteration between the start and stop numbers.
class PizzaCounter:
def __init__(self, start, stop):
self.num = start
self.stop = stop
def __iter__(self):
return self
def __next__(self):
if self.num > self.stop:
raise StopIteration
else:
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)
try:
while True:
print ("Eating Pizzas, couter ", next(obj))
except:
print ("\n Done Pizzas, GAME OVER")
Let us execute the above program and see the output.
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.
Syntax is
class MyNumbers:
def __iter__(self):
-- Operation --
return self
def __next__(self):
Terminating Condition
-- Operation –
return x
else:
raise StopIteration
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.
Output
Conclusion
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!